【问题标题】:How to join the results of 2 tables side-by-side?如何并排连接 2 个表的结果?
【发布时间】:2013-12-06 07:12:10
【问题描述】:

我有 2 个查询将 2 个结果复制为:

结果 1:

select title1,age1 from tab1 where title1 in ('1','2')

title1 age1 
1       2
2       3

结果 2:

select title2,age2 from tab2 where title2 in ('a','c')

title2 age2
a       b
c       d

我希望我的结果简单地并排连接在一起作为最终结果:

title1 age1 title2 age2
1       2     a        b
2       3     c        d

如何以简单的方式实现这一目标?我搜索了但没有找到解决方案。

== 更新表的架构

+--------+---------+------+-----+---------+-------+
| Field  | Type    | Null | Key | Default | Extra |
+--------+---------+------+-----+---------+-------+
| title1 | int(11) | YES  |     | NULL    |       |
| age1   | int(11) | YES  |     | NULL    |       |
+--------+---------+------+-----+---------+-------+
2 rows in set (0.01 sec)

mysql> describe tab2;
+--------+------------+------+-----+---------+-------+
| Field  | Type       | Null | Key | Default | Extra |
+--------+------------+------+-----+---------+-------+
| title2 | varchar(2) | YES  |     | NULL    |       |
| age2   | varchar(2) | YES  |     | NULL    |       |
+--------+------------+------+-----+---------+-------+

=== 更新: 我尝试了以下操作:

select * from 
(select title1, age1 from tab1 order by title1,age1) as result1 , 
(select title2, age2 from tab2 order by title2,age2) as result2 ; 

它产生了 4 行:

+--------+------+--------+------+
| title1 | age1 | title2 | age2 |
+--------+------+--------+------+
|      1 |    2 | a      | b    |
|      2 |    3 | a      | b    |
|      1 |    2 | c      | d    |
|      2 |    3 | c      | d    |
+--------+------+--------+------+

【问题讨论】:

  • 欢迎来到 Stack Overflow!请edit您的问题包含您的查询代码。
  • 发布您的表架构。什么是关系列(如果有)?
  • 子查询中无限制的顺序没有意义,任何顺序都是巧合。

标签: mysql sql join


【解决方案1】:

我认为这对你有好处。

-- 例子

select result1.title1, title1.age1,result2.title2, title2.age2 from 
  (select @i:=@i+1 AS rowId, title1, age1 from tab1,(SELECT @i:=0) a) as result1 , 
  (select @j:=@j+1 AS rowId,title2, age2 from tab2,(SELECT @j:=0) a ) as result2 
where 
  result1.rowId = result2.rowId; 
-- try this it will work perfectly fine

【讨论】:

  • 试过这个。它产生的结果与“交叉连接”相同,最后有 4 行。我只想要 2 行。
  • 尝试了所有查询。全部产生 4 行而不是 2 行。
  • 您可以使用where子句添加条件以删除重复的列。
  • 我已经编辑了答案,这对你来说非常好,没有一个关键的列可以加入。
  • 只是为了添加在 Oracle 中提供了 rowID 和 rowNum 但在 MYSQL 中没有,所以我只是使用了一种解决方法来做同样的事情
【解决方案2】:

没有看到你的 SQL 查询,很难给你一个准确的答案,但你应该把它们合并在一起,像这样:

SELECT  title_1, age_1, title_2, age_2
FROM    table1, table2
WHERE   table1.id = table2.id

【讨论】:

  • 添加了查询命令。你的方式是先加入再选择。我想先选择然后加入。
【解决方案3】:
select title_1, age_1 from table1
union
select title_2, age_2 from table2

结果是

title_1 age_1 title_2 age_2
1       2     
2       3    
              a        b
              c        d

【讨论】:

    猜你喜欢
    • 2023-03-23
    • 2013-09-03
    • 2022-12-22
    • 2015-07-29
    • 1970-01-01
    • 2017-12-22
    • 2014-06-10
    • 2016-06-02
    • 2015-08-19
    相关资源
    最近更新 更多