【问题标题】:combining two selects next o each other, not on top of the other将两个选择组合在一起,而不是在另一个之上
【发布时间】:2012-04-23 02:25:49
【问题描述】:

我的 MySQL 数据库中有这个结构:

   +--------------+    +--------------+
   |    table_1   |    |    table_2   | 
   +----+---------+    +----+---------+  
   | id |   name  |    | id | surname |  
   +----+---------+    +----+---------+  
   | 1  | tbl1_1  |    | 1  | tbl2_1  |  
   | 2  | tbl1_2  |    | 2  | tbl2_2  |   
   | 3  | tbl1_3  |    | 3  | tbl2_3  |  
   +----+---------+    +----+---------+   

我需要一个返回这个的查询:

   +----+---------+---------+
   | id |   name  | surname |
   +----+---------+---------+
   | 2  | tbl1_2  | tbl2_2  |
   +----+---------+---------+

我在谷歌搜索,我发现是 UNION 这样做:

   +----+---------+
   | id |  name   |
   +----+---------+
   | 2  | tbl1_2  | 
   | 2  | tbl2_3  |
   +----+---------+  

这不是我想要的。我需要将它们彼此相邻组合,而不是彼此重叠。

【问题讨论】:

  • 你能举个例子吗。

标签: mysql merge


【解决方案1】:

您需要使用JOIN,连接类型取决于您的要求。

SELECT id,name,surname FROM table_1 INNER JOIN table_2 on table_2.id=table_1.id WHERE table_1.id = 2

INNER JOIN 将选择两个表中的所有行,只要我们匹配的 id 列之间存在匹配,即两个表中都存在 ids

【讨论】:

  • 不,它只是选择所有行,我还需要应用 WHERE 子句。
【解决方案2】:

这是必须要做的:

SELECT table_1.id, name, surname FROM table_1, table_2 WHERE table_1.id = 2 AND table_2.id = 2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-27
    • 2017-04-19
    • 2011-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    相关资源
    最近更新 更多