从具有不同条件的2个表中选择

时间:2015-02-17 09:59:42

标签: mysql select join multi-query

我试图让这个约2个小时没有成功。以下是我需要做的一个例子:

表格

people

nameA           score
---------------------
someone1        24
someone2        24
someone3        24
someone4        23
someone5        21
someone6        24
someone7        19
someone8        20
someone9        24
someone10       24

runs

nameB           add
---------------------
someone1        s
someone2
someone2
someone4        s
someone5
someone4
someone7        s
someone8        s
someone7
someone7        s

请注意,这只是一个可视化显示我的问题的示例。无需谈论我的桌子设置。

我想知道的事情:
首先,我需要表people中所有条目,其中得分小于24(这里很容易)。

下一步是仅显示表s中people.name没有runs的结果(我的实际问题)。

输出应为:

name            score
---------------------
someone2        22      /*  no "s"-entry in runs        */
someone5        21      /*  also no entries             */

不幸的是,我不太熟悉联接。 这是我的最后一次尝试:

SELECT nameA,score FROM runs,people WHERE people.nameA = runs.nameB
AND people.score < 24
AND runs.add != "s"
GROUP BY people.nameA

伪代码:

foreach Person in (SELECT nameA as Person,score FROM people WHERE score < 24)
SHOW name.B = Person WHERE add != "s"

我知道这是狗屎:)。但它描述了我需要的两行。

我很感激这里有任何帮助 谢谢!

2 个答案:

答案 0 :(得分:2)

select * from people where score<24 and 
name in (select name from runs where add!=s) and
name not in (select name from runs where add=s)

答案 1 :(得分:1)

SELECT people.nameA,runs.score FROM runs,people WHERE people.nameA = runs.nameB
AND people.score < 24
AND people.nameA NOT IN (SELECT runs.nameB FROM RUNS WHERE runs.add = "s")
GROUP BY people.nameA