SQL:匹配多列值

时间:2011-09-26 18:00:41

标签: sql

我设置了一个数据库,以便用户名(username)和id(id)存储在members表中。

我有另一个记录报告的表,我记录了表(fid)中的每一列,谁报告了它(摆脱),他们报告的是谁(id),它们都与成员表中用户的id匹配。

如何获取查询以获取rid和id的用户名?

我当前的查询是

SELECT selfreport.fid, selfreport.rid, 
       selfreport.id, members.username as username
FROM members, selfreport
WHERE members.id = selfreport.id
ORDER BY fid

但这只会获取他们报告对象的用户名。如何让它为两者提取用户名?

3 个答案:

答案 0 :(得分:3)

您需要两次加入您的会员表。尝试这样的事情:

SELECT      selfreport.fid,
            selfreport.rid,
            selfreport.id,
            COALESCE(WhoReported.username, 'Not Specified') AS WhoReportedUN,
            COALESCE(ReportedTo.username, 'Not Specified') AS ReportedToUN
FROM        selfreport
LEFT JOIN   members WhoReported ON WhoReported.id = selfreport.id
LEFT JOIN   members ReportedTo ON ReportedTo.id = selfreport.rid
ORDER BY    fid

答案 1 :(得分:2)

您需要加入members两次:

SELECT selfreport.fid, 
       selfreport.rid, 
       selfreport.id, 
       m1.username AS ReportToUsername, 
       m2.username AS ReporteeUsername 
FROM   selfreport 
       INNER JOIN members m1 
         ON m1.id = selfreport.id 
       INNER JOIN members m2 
         ON m2.id = selfreport.rid 
ORDER  BY fid 

由于您在原始查询中进行了隐式连接,因此我相信INNER JOIN会很适合您。但是,如果selfreport.idselfreport.rid中可以包含空值,则应使用LEFT JOIN代替。

答案 2 :(得分:2)

不要使用隐式SQL '89连接,它们是反模式 请改用显式连接语法。

SELECT s.fid, s.rid, s.id, m1.username as username, m2.username as rusername
FROM selfreport S
INNER JOIN members m1 ON (m1.id = s.id)
INNER JOIN members m2 ON (m2.id = s.rid)
ORDER BY s.fid

如果idrid是可选的,请使用左连接。

SELECT 
  s.fid, s.rid, s.id
  , COALESCE(m1.username, 'nobody') as username
  , COALESCE(m2.username, 'nobody') as rusername
FROM selfreport S
LEFT JOIN members m1 ON (m1.id = s.id)
LEFT JOIN members m2 ON (m2.id = s.rid)
ORDER BY s.fid