加入多行相同的表

时间:2013-01-28 20:53:45

标签: php sql

我试图从1个表中提取2组不同的数据。我不太清楚如何处理这个问题。这是当前设置的表(相关)。

+----+-----------+----------+------+------------+--------+--------+
| 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  |
+----+----------+

我可以使用此查询让收件人与姓名匹配:

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

这会将收件人72与user72匹配,但我也希望将1给出以显示admin和given_by 4以显示为user4。

2 个答案:

答案 0 :(得分:3)

试试这个:(您需要做的就是别名对DD_users表的第二个引用,并添加第二个连接语句,然后在select语句中引用别名用户名列。)

  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

答案 1 :(得分:2)

您需要在DD_users表格中加入两次,一次是id,而另一次是given_by。每个都有自己的别名,必须在SELECT列表中使用它来消除歧义(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