mysql - 将两个表中的记录合并到一个查询中

标签 mysql database sqlite

我有下表,

从表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/

相关文章:

php - 从存储在mysql中的路径显示图像

mysql - COUNT(*) 是否总是返回结果?

mysql - 使用 Golang 将 SQL 查询结果放入嵌套结构中

SQL 将具有多个小数的字符串转换为整数

php - MySQL数据库不同的插入

sql - 从 Postgresql 表中绘制表和关系

sql - 使用触发器更新多个表

sql - 在两列之间选择最近的日期

c - 如何使用 C-API 执行 sqlite 的点命令

sql - 检查TEXT列的内容是否为纯数字