2

我正在尝试从 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 相匹配,但我也想让 given by 1 显示 admin 和 given_by 4 显示为 user4。

4

2 回答 2

3

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

  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
于 2013-01-28T20:58:30.523 回答
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
于 2013-01-28T20:57:08.707 回答