在一个查询中组合来自两个表的记录

时间:2014-07-09 15:33:04

标签: mysql database sqlite

我有以下表格,

从tbl1中选择*;

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

从tbl2中选择*;

+------+------------+---------+-------------+------------+-----------+
| 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

1 个答案:

答案 0 :(得分:0)

您想使用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;
相关问题