0

I have a problem with my query results. I have 2 tables that I want to join with specific join to get all the informations about it and a or condition that doesnt include second table. There is my tables :

main_orders:

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

includes:

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

here id number 1 is the main order and it also covers the rest of the orders show as in the second table with rel_id

i want to select the order details of id 1 from main_orders and also the orders that relate to this id

my query is,

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

it works only when there is any relative orders in the second table, please help the result should be as follows

RESULTANT ROWS:

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

Thanks

4

4 回答 4

3

你可以使用exists子句:

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

于 2013-10-11T17:02:58.383 回答
0

也许是这样的?

从 a.id=b.id GROUP BY a.id 的左连接 b 中选择 a.id;

(显然使用你的表名)

于 2013-10-11T16:56:42.077 回答
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上查看。

于 2013-10-11T17:01:52.397 回答
0

尝试这个。

SELECT a.id FROM main_orders a, includes b
where (b.id=1 and (a.id=b.rel_id or a.id=1 ))
于 2013-10-11T17:21:25.247 回答