SQL SELECT WHERE子查询(多行)=子查询(多行)

时间:2015-06-04 08:48:43

标签: sql sql-server

原谅长度,这很难解释!

我有两张桌子:

1
然后我执行以下语句:

t_people
----------------------------------------
|  ID       |  surname   |  forenames  |
----------------------------------------
|  1        |  Baggins   |  Frodo      |
----------------------------------------
|  2        |  Took      |  Peregrin   |
----------------------------------------
|  3        |  Baggins   |  Bilbo      |
----------------------------------------

t_courseResults
--------------------------
|  personID |  result    |
--------------------------
|  1        |  98.0%     |
--------------------------
|  2        |  14.0%     |
--------------------------
|  3        |  56.0%     |
--------------------------

...返回姓氏以“B”(2行)开头的所有人的所有课程结果。

现在假设我有第三个表存储静态人员列表(例如特定部门的人员列表)

SELECT result FROM t_courseResults WHERE personID IN (SELECT ID FROM t_people WHERE surname like '%B')

然后我想执行这样的事情:

t_staticList
-------------
|  personID |
-------------
|  2        |
-------------
|  3        |
-------------

这显然是垃圾,但是这样的事情可能还是我是傻瓜?我的想法是,这将只返回一行--Bilbo Baggins - 因为他的名字以'B'开头,而他在t_staticList表中。谢谢!

4 个答案:

答案 0 :(得分:1)

使用INNER JOIN

SELECT A.result
FROM t_courseResults AS A, t_staticList AS B
    INNER JOIN t_people AS C ON c.id = B.personID 
WHERE c.surname like '%B'

答案 1 :(得分:0)

你的意思是这样吗?

SELECT result FROM t_courseResults WHERE PersonId IN (
  SELECT p.ID FROM t_staticList AS s
  INNER JOIN t_people as p ON p.ID = s.PersonId
  WHERE p.surname like '%B')

答案 2 :(得分:0)

如果我理解正确你试图做这样的事情:

SELECT result 
FROM t_courseResults 
WHERE personID IN 
   (SELECT p.ID FROM t_people p INNER JOIN t_staticList s ON p.PersonID = s.PersonID WHERE surname like '%B')

答案 3 :(得分:0)

从t_people选择*内部联接t_courseResults B在A.ID = B.personID上 内部联接t_staticList C on C.personID = B.personID和A.surname like('B%')