【问题标题】:Combine records from two tables in one query在一个查询中合并来自两个表的记录
【发布时间】:2014-07-09 15:33:03
【问题描述】:

我有以下表格,

从 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

【问题讨论】:

    标签: mysql database sqlite


    【解决方案1】:

    你想使用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;
    

    【讨论】:

      猜你喜欢
      • 2013-11-22
      • 2018-09-21
      • 2018-05-29
      • 2020-10-12
      • 2013-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多