2012-07-07 46 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