如何从一个表中连接两个长查询?

时间:2012-07-07 11:58:20

标签: mysql join

我有专栏

First name | last name | nr (individual number) | pref1 (preference1) | pref2 (preference2)| pref3(preference3) | situation | distance | sex

在一个表ap中有100条记录

在所有的结果我不能有裁员。这意味着当在第一组结果中我得到前例'2112'的个别数字(列“nr”)时,它不能显示在最后一个结果中。

SELECT DISTINCT nr FROM ap 

首次查询记录:

WHERE sex='F' and pref1='1' ORDER BY situation DESC, distance DESC
AND  WHERE (sex='F' and pref2='1' and situation= ' ' ) ORDER BY distance DESC
and WHERE (sex='F' and pref3='1' and situation= ' ' ) ORDER BY distance DESC
LIMIT 4

然后我想加入第二个查询的结果:

WHERE sex='M' and pref1='2' ORDER BY situation DESC, distance DESC
AND WHERE (sex='M' and pref2='2' and situation= ' ' ) ORDER BY distance DESC
AND WHERE (sex='M' and pref3='2' and situation= ' ' ) ORDER BY distance DESC
LIMIT 7

然后加入上次查询的所有记录:

WHERE sex='F' and pref1='3' ORDER BY situation DESC, distance DESC
AND WHERE (sex='F' and pref2='3' and situation= ' ' ) ORDER BY distance DESC
AND WHERE (sex='F' and pref3='3' and situation= ' ' ) ORDER BY distance DESC
LIMIT 10

有可能吗?

2 个答案:

答案 0 :(得分:0)

尝试使用UNION,这只是一个使用UNION的简单示例

答案 1 :(得分:0)

SELECT DISTINCT nr FROM  
(select distinct nr from ap WHERE sex='F' and pref1='1' ORDER BY situation DESC,   distance DESC Union
select distinct nr from ap WHERE (sex='F' and pref2='1' and situation= ' ' ) ORDER BY distance DESC union
select distinct nr from ap WHERE (sex='F' and pref3='1' and situation= ' ' ) ORDER BY distance DESC union
LIMIT 4)
UNION
(select distinct nr from ap WHERE sex='M' and pref1='2' ORDER BY situation DESC,   distance DESC union
select distinct nr from ap WHERE (sex='M' and pref2='2' and situation= ' ' ) ORDER BY distance DESC union
select distinct nr from ap WHERE (sex='M' and pref3='2' and situation= ' ' ) ORDER BY distance DESC union
LIMIT 7
)
UNION
(select distinct nr from ap WHERE sex='F' and pref1='3' ORDER BY situation DESC,   distance DESC union
select distinct nr from ap WHERE (sex='F' and pref2='3' and situation= ' ' ) ORDER BY distance DESC union
select distinct nr from ap WHERE (sex='F' and pref3='3' and situation= ' ' ) ORDER BY distance DESC union
LIMIT 10
))