我正在尝试连接两个表,这样我只能从Right表中获得第一个匹配,而不是Table2中的每个匹配。
所以如果查询是:
SELECT T1.Name, T2.Dates
FROM Table1 T1
LEFT JOIN Table2 T2 ON T1.ID = T2 = ID
WHERE T1.Name = 'John'
我想看看
John | 14/11/14
Joe | 10/10/2014
Jane | 25/10/2014
而不是
John | 14/11/2014
John | 12/10/2014
Joe | 10/10/2014
Jane | 25/10/2014
Jane | 26/10/2014
我应该使用哪种联接?
答案 0 :(得分:1)
您需要决定选择哪一行。最小或最大评论。
SELECT T1.Name,
( SELECT MIN( T2.Dates) FROM Table2 T2 WHERE T1.ID = T2 = ID) AS Dates
FROM Table1 T1
WHERE T1.Name = 'John'
答案 1 :(得分:1)
ANSI标准函数row_number()
在这里可以提供很大的帮助。大多数数据库都支持它,因此您可以这样做:
SELECT T1.Name, T2.Dates
FROM Table1 T1 LEFT JOIN
(SELECT t2.*, ROW_NUMBER() OVER (PARTITION BY t2.ID ORDER BY t2.DATE DESC) as seqnum
FROM Table2 t2
) T2
ON T1.ID = T2.ID AND seqnum = 1
WHERE T1.Name = 'John';
在您的问题中,您只有第二个表中的一列,因此您也可以通过聚合执行此操作:
SELECT t1.ID, t1.Name, MAX(t2.Date)
FROM Table1 T1 LEFT JOIN
Table2 T2
ON t1.ID = t2.ID
WHERE T1.Name = 'John'
GROUP BY t1.ID, t1.Name;
答案 2 :(得分:0)
SELECT a.name,
MAX(b.Dates)
FROM tbl1 a
JOIN tbl2 b
ON a.id=b.id
WHERE a.name='John'
GROUP BY a.name;