2012-07-07 77 views
0

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

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

与100只记录在一个表中AP

在所有我不能有冗余的结果。这意味着当第一组结果中我得到前面的例子'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 

是否有可能t做什么?

+0

既然你展示SQL是无效的,这是很清楚你是什么后,只是一个简单的例子。你能不能展示一些示例表格行以及你的查询输出结果的样本? – 2012-07-07 12:01:57

回答

0

尝试使用UNION,它是使用UNION

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 
)) 
+0

联合只会选取不同的行 – 2012-07-07 12:07:36

+0

关系演算并不能确保,但可能在MYSQL/ORACLE中你说的是对的。 – Razvan 2012-07-07 12:09:42

+0

这不像有效的SQL。每个工会组有多个'WHERE'和多个'ORDER BY'?不工作... – 2012-07-07 12:24:05