2016-07-05 36 views
0

獲取記錄我有兩個表:從一個表和一個對應表

orders 
poid | user | pid | payment_id 
1 | 1 | 1 | abc123 
2 | 2 | 2 | def345 

orders_addon 
poaid | user | poid | pid 
1  | 1 | 1 | 3 
2  | 1 | 1 | 5 

一個表示訂單,第二個代表插件,用戶可以添加到他的命令。

訂單總是有一排,並且可能會發生訂單沒有匹配的orders_addon。

我正在查找從訂單和orders_addon返回匹配行的查詢,如果匹配的話。

SELECT用戶,PID FROM ... WHERE payment_id = 'ABC123'

應該返回

user | pid 
1 | 1 
1 | 3 
1 | 5 

而且如果在沒有匹配的記錄相同的查詢應該只返回Orders表結果orders_addon表。

SELECT用戶,PID FROM ... WHERE payment_id =「def345」

user | pid 
2 | 2 

我想這可能使用UNION做,但後來我就沒法匹配表,它會成爲一個由於orders_addon表問題沒有payment_id

回答

0

使用留下了IF STATMENT JOIN

mysql> (SELECT u.user,IFNULL(ua.pid ,u.pid) as pid 
      FROM orders u 
      inner JOIN orders_addon ua on ua.poid=u.poid 
      WHERE u.payment_id = 'abc123' 
     ) 
    union all 
     (SELECT u.user,u.pid 
      from orders u 
      where u.payment_id = 'def345' 
    ); 
+------+------+ 
| user | pid | 
+------+------+ 
| 1 | 3 | 
| 1 | 5 | 
| 2 | 2 | 
+------+------+ 
3 rows in set (0.00 sec) 

mysql> (SELECT u.user,IFNULL(ua.pid ,u.pid) as pid 
      FROM orders u 
      inner JOIN orders_addon ua on ua.poid=u.poid 
      WHERE u.payment_id = 'def345' 
     ) 
    union all 
     (SELECT u.user,u.pid 
      from orders u 
      where u.payment_id = 'def345' 
     ); 

+------+------+ 
| user | pid | 
+------+------+ 
| 2 | 2 | 
+------+------+ 
1 row in set (0.00 sec) 
+0

,請試試這個,讓我知道 –

+0

對於與第一實施只返回2行,訂單表的結果丟失。 – maddo7

+0

@ maddo7更新查詢請現在檢查 –