从一个表和相应的表中获取记录

时间:2016-07-05 09:57:25

标签: mysql join union innodb

我有两张桌子:

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 user,pid FROM ... WHERE payment_id ='abc123'

应该返回

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

如果orders_addon表中没有匹配的记录,同样的查询应该只返回orders表中的结果。

SELECT user,pid FROM ... WHERE payment_id ='def345'

user | pid
2    | 2

我认为这可以使用UNION来完成但是后来我无法匹配表格,因为orders_addon表没有payment_id

它会成为一个问题

1 个答案:

答案 0 :(得分:0)

使用LEFT JOIN WITH IF STATMENT

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)