简体   繁体   中英

Get records from one table and a corresponding table

I have two tables:

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

One represents orders, the second one represent addons a user can add to his order.

There is always a row in orders and it can occur that there is no matching orders_addon for an order.

I'm looking for a query that returns matching rows from orders and orders_addon if there are matching ones.

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

Should return

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

And the same query should only return results from the orders table if there is no matching record in the orders_addon table.

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

user | pid
2    | 2

I reckon this could be done using UNION but then I wouldn't be able to match the tables and it would become a problem since the orders_addon table doesn't have a payment_id

Use 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM