简体   繁体   中英

Combine records from two tables in one query

I have the following tables,

select * from tbl1;

+------+------------+---------+----------+
| id   | userId     | part_id | url      |
+------+------------+---------+----------+
|    1 | 155        |       1 | "http:/" |
+------+------------+---------+----------+

select * from tbl2;

+------+------------+---------+-------------+------------+-----------+
| id   | userId     | part_id | tbl2_id1    |   tbl2_id2 | notes     |
+------+------------+---------+-------------+------------+-----------+
|    1 | 155        |       1 |  12         |          1 | note 1    |
|    2 | 155        |       1 |  12         |          2 | note 2    |
+------+------------+---------+-------------+------------+-----------+

As you can see tbl2 has two FK (userId and part_id), tbl2_id1 and tbl2_id2 are the PK of tbl2.

My question is how can I get the three records from both tables in one query?

Something like this

  1 | 155        |       1 |"http:/"   | from tbl1
  1 | 155        |       1 | note 1    | from tbl2
  2 | 155        |       1 | note 2    | from tbl2

You want to use union all :

select id, userId, part_id, url, 'from tbl1' as which
from tbl1
union all
select id, userId, part_id, notes, 'from tbl2'
from tbl2;

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