2013-10-11 39 views
0

我的查詢結果出現問題。我有2個表,我想要加入特定的連接,以獲得有關它的所有信息和不包含第二個表的條件。還有就是我的表:與OR子句連接兩個表

main_orders: 

id | destination 
---------- 
1 | London 
2 | Germany 
2 | Netherland 
3 | Polska 
4 | JP 

includes: 

id | rel_id 
---------- 
1 | 2 
1 | 3 

這裏id號1是主秩序,同時也涵蓋了訂單的剩餘部分顯示爲第二表rel_id

我想選擇ID的訂單詳情1從main_orders和也是涉及到這個ID

我查詢訂單,

SELECT a.id FROM main_orders a, includes b 
where (a.id = 1) OR (b.id = 1 and a.id = b.rel_id) 

它的工作原理時,纔會有第二個表的任何相對訂單,請幫助的結果應該是如下

RESULTANT ROWS: 

id | destination 
---------- 
1 | London 
2 | Germany 
2 | Netherland 
3 | Polska 

感謝

+0

通過使用'SELECT a.id FROM main_orders a,包括b',您創建了一個交叉連接,它是您的表的笛卡爾乘積。你應該使用一個內部連接和一個where子句 –

+0

你是否真的認爲'main_orders.id'是非唯一的?該表中的PK是什麼? – eggyal

+0

PK是另一列名爲串行,它是自動增量 –

回答

0

也許這樣的事情?

SELECT a.id FROM LEFT JOIN b on a.id = b.id GROUP BY a.id;

(顯然是用你的表名)

+0

試過,該查詢不起作用,它給出了與我的查詢012相同的副本 –

+0

您到那時需要一個組。編輯添加分組 – mjr

0
SELECT  main_orders.id, main_orders.destination 
FROM  main_orders 
    LEFT JOIN includes ON includes.rel_id = main_orders.id 
WHERE  main_orders.id = 1 OR includes.id = 1 

見它sqlfiddle

3

你可以使用一個存在的條款:

SELECT a.id, a.destination FROM 
main_orders a 
where a.id = 1 
or exists (select null 
          from includes b 
          where b.rel_id = a.id 
          and b.id =1); 

看到sqlFiddle

+0

這個問題,它也提取不涉及的ID –

+0

SELECT a.id,a.destination FROM main_orders a 其中a.id = 1 或存在(從null中選擇null from includes b 其中b.id = 1和b.rel_id = a.id); –

+0

上面的查詢工作我添加b.id = 1,它的工作 –

0

試試這個。

SELECT a.id FROM main_orders a, includes b 
where (b.id=1 and (a.id=b.rel_id or a.id=1))