2010-06-09 95 views
2

我必須從兩個表中查詢並希望得到一個結果..我如何加入這兩個查詢?加入兩個Oracle查詢

第一個查詢是從兩個表中查詢,第二個查詢只能從一個查詢。

select pt.id,pt.promorow,pt.promocolumn,pt.type,pt.image,pt.style,pt.quota_allowed,ptc.text,pq.quota_left 

from promotables pt,promogroups pg ,promotablecontents ptc ,promoquotas pq where pt.id_promogroup = 1 and ptc.country ='049' and ptc.id_promotable = pt.id and pt.id_promogroup = pg.id and pq.id_promotable = pt.id order by pt.promorow,pt.promocolumn 

select pt.id,pt.promorow,pt.promocolumn,pt.type,pt.image,pt.style,pt.quota_allowed from promotables pt where pt.type='heading' 
+0

你想加入查詢或將它們連接起來?這些在SQL中意味着不同的東西。連接通常意味着連接標準(從a.col = b.col'上的連接b中選擇),而連接只是將一個查詢的結果附加到另一個查詢(例如,通過'UNION'或'UNION ALL')。 – 2010-06-10 02:54:53

回答

4

使用UNION或UNION ALL。只要你有相同數量的列,並且它們是兼容的類型,應該可以做你想做的。

SELECT pt.id, pt.promorow, pt.promocolumn, pt.type, pt.image, pt.style, pt.quota_allowed, ptc.text, pq.quota_left 
FROM promotables pt, promogroups pg, promotablecontents ptc, promoquotas pq 
WHERE pt.id_promogroup = 1 
AND ptc.country ='049' 
AND ptc.id_promotable = pt.id 
AND pt.id_promogroup = pg.id 
AND pq.id_promotable = pt.id 
UNION 
SELECT pt.id, pt.promorow, pt.promocolumn, pt.type, pt.image, pt.style, pt.quota_allowed, NULL, NULL 
FROM promotables pt 
WHERE pt.type='heading' 
ORDER BY 2, 3 

如果你想顯示重複(例如相同的行從兩個查詢來),使用UNION ALL

+0

對於第一個查詢,數字結果列更多.. – coder247 2010-06-09 08:57:41

+0

只需爲其他查詢中的列選擇NULL即可。這意味着您仍然可以獲得列,並且查詢1的結果可能有數據,而來自查詢2的行將始終包含這些列的NULL。 – 2010-06-09 09:00:07