从给定ID表的表中选择相似的行

时间:2012-02-07 17:30:40

标签: sql sql-server select

我有两张桌子。

Table A

+----+-------+--------+-------+-------+
| ID | First | Middle | Last  | Time  |
+----+-------+--------+-------+-------+
| 1  | John  | Alan   | Smith | 12:38 |
+----+-------+--------+-------+-------+
| 2  | John  | Alan   | Smith | 1:24  |
+----+-------+--------+-------+-------+
| 3  | John  | Alan   | Bauer | 1:24  |
+----+-------+--------+-------+-------+
| 4  | Sam   | Paul   | West  | 10:04 |
+----+-------+--------+-------+-------+

Table B

+----+
| ID |
+----+
| 2  |
+----+
| 4  |
+----+

由此,我需要创建一个SELECT查询,以获得表A的行,其FirstMiddleLast值与{{1}相匹配表B中First的{​​},MiddleLast值。

换句话说,我需要得到

ID

所以我们选择了第2行和第4行,因为它们在表B中,但我们也选择了第1行,因为它的Table C +----+-------+--------+-------+-------+ | ID | First | Middle | Last | Time | +----+-------+--------+-------+-------+ | 1 | John | Alan | Smith | 12:38 | +----+-------+--------+-------+-------+ | 2 | John | Alan | Smith | 1:24 | +----+-------+--------+-------+-------+ | 4 | Sam | Paul | West | 10:04 | +----+-------+--------+-------+-------+ FirstMiddle值与第2行中的值相匹配

我们没有选择第3行,因为它的Last值不在表B的任何行中。

我希望这是有道理的。我不知道该如何解决这个问题。我在考虑在A和B上使用Last,但后来我不确定如何从那里选择相似的行。

5 个答案:

答案 0 :(得分:3)

这应该可以解决问题:

select A.* from TableA A
inner join TableA A2 on A.First = A2.First and A.Middle = A2.Middle and A.Last = A2.Last
and A2.ID in (select ID from TableB)

答案 1 :(得分:1)

尝试:

select *
from TableA a
where exists
(select null
 from TableA a1
 join TableB b on a1.ID = b.ID
 where a.First = a1.First and a.Middle = a1.Middle and a.Last = a1.Last)

答案 2 :(得分:1)

无需使用完整的内部联接或子查询。表别名和两个左连接将为您执行此操作,我相信这比任何其他已发布的替代方案更有效。请参阅此处以获取有效的证据:http://sqlfiddle.com/#!2/11361/1

SELECT c.*
FROM b
LEFT JOIN a ON b.id = a.id
LEFT JOIN a AS c ON
  c.first = a.first AND
  c.middle = a.middle AND
  c.last = a.last

这实际上构建的东西非常类似于您要查找的表c并从中选择所有行(SELECT c.*)。

它遵循与您思考方式相同的逻辑:

  • 从表b(FROM b)中的ID开始。
  • 查找表a(LEFT JOIN a ON b.id = a.id)。
  • 中的相应行
  • 最后,从表a中选择也匹配(LEFT JOIN a AS c ON c.first = a.first AND c.middle = a.middle AND c.last = a.last)的所有行。
  • 就是这样,你现在有一张表c,看起来就像你想要的一样。

答案 3 :(得分:0)

试试这个:

SELECT    TA2.ID,
          TA2.First,
          TA2.Middle,
          TA2.Last,
          TA2.Time
FROM      TableA AS TA INNER JOIN
          TableB AS TB ON TB.ID = TA.ID LEFT JOIN
          TableA AS TA2 ON TA2.First = TA.First AND
              TA2.Middle = TA.Middle AND
              TA2.Last = TA.Last

答案 4 :(得分:0)

SELECT A2.ID, A2.First, A2.Middle, A2.Last, A2.Time
FROM A AS A
INNER JOIN B AS B ON A.ID = B.ID
INNER JOIN A AS A2 ON
    A.First = A2.First AND
    A.Middle = A2.Middle AND
    A.Last = A2.Last