我有下表,
从表1中选择*;
+------+------------+---------+----------+
| id | userId | part_id | url |
+------+------------+---------+----------+
| 1 | 155 | 1 | "http:/" |
+------+------------+---------+----------+
从表2中选择*;
+------+------------+---------+-------------+------------+-----------+
| id | userId | part_id | tbl2_id1 | tbl2_id2 | notes |
+------+------------+---------+-------------+------------+-----------+
| 1 | 155 | 1 | 12 | 1 | note 1 |
| 2 | 155 | 1 | 12 | 2 | note 2 |
+------+------------+---------+-------------+------------+-----------+
可以看到tbl2有两个FK(userId和part_id),tbl2_id1和tbl2_id2是tbl2的PK。
我的问题是如何在一个查询中从两个表中获取三条记录?
类似这样的
1 | 155 | 1 |"http:/" | from tbl1
1 | 155 | 1 | note 1 | from tbl2
2 | 155 | 1 | note 2 | from tbl2
最佳答案
您想要使用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;
关于mysql - 将两个表中的记录合并到一个查询中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24657879/