I am trying to pull 2 different sets of data off of 1 table. I am not quite sure how to approach this though. This is the current table set up (that pertinent).
+----+-----------+----------+------+------------+--------+--------+
| id | recipient | given_by | time | expiration | points | reason |
+----+-----------+----------+------+------------+--------+--------+
| 1 | 72 | 1 | time | time | 2 | test |
| 3 | 15 | 4 | time | time | 5 | test |
+----+-----------+----------+------+------------+--------+--------+
+----+----------+
| id | username |
+----+----------+
| 1 | admin |
| 4 | user4 |
...
| 15 | user15 |
...
| 72 | user72 |
+----+----------+
I was able to get the recipient to match up to a name by using this query:
SELECT
usr.username, usr.id, sl.recipient, sl.given_by,
sl.time, sl.experation, sl.points, sl.reason
FROM
DD_users AS usr
LEFT JOIN
DD_schittlist AS sl
ON (sl.recipient = usr.id)
GROUP BY
usr.id
ORDER BY
sl.points DESC,
usr.username
That will match up recipient 72 to user72 but I also want to make given by 1 to show admin and given_by 4 to show as user4.
You need to join twice against the DD_users
table, once for id
as you already have, and another for given_by
. Each gets its own alias, which must be used in the SELECT
list to disambiguate them (usr, given
)
SELECT
/* The original username you already had */
usr.username,
usr.id,
sl.recipient,
sl.given_by,
/* The given_by username from the given alias table */
/* Be sure to alias this column here as well to differentiate them in the client */
given.username AS given_by_username,
sl.time,
sl.experation,
sl.points,
sl.reason
FROM
DD_users AS usr
/* First join you already had between id and recipient */
LEFT JOIN DD_schittlist AS sl ON (sl.recipient = usr.id)
/* A second LEFT JOIN between DD_shittlist and DD_users as given */
/* (LEFT JOIN permits nulls in DD_shittlist.given_by) */
LEFT JOIN DD_users AS given ON sl.given_by = given.id
GROUP BY
usr.id
ORDER BY
sl.points DESC,
usr.username
Try this: (All you need to do is alias a 2nd reference to the DD_users table and add a 2nd join statement, then reference the aliased username column in your select statement.)
SELECT
usr.username, usr.id, sl.recipient, sl.given_by, usr2.username, sl.time, sl.experation, sl.points, sl.reason
FROM
DD_users AS usr
LEFT JOIN DD_schittlist AS sl ON (sl.recipient = usr.id)
JOIN DD_users as usr2 ON (usr2.id = sl.given_by)
GROUP BY
usr.id
ORDER BY
sl.points DESC,
usr.username