mysql - 如何并排连接两个表的结果?

标签 mysql sql join

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

最佳答案

我认为这对你有好处。

-- 示例

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

关于mysql - 如何并排连接两个表的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20418158/

相关文章:

php - MYSQL JOIN 递增 id

mysql - 如何逐行更新从过程中的游标检索的数据库值?

当使用 COUNT 与 LEFT OUTER JOIN 和 GROUP BY 时,MySQL 包含零行

mysql - 在查询结果中,防止系列中最后一个数字后面出现逗号

php - fatal error 说明 "Call to a member function bind_param() on a non-object"

mysql - SQL 多表 JOINS、GROUP BY 和 HAVING

mysql - 拼写错误3 : CASE not working with additional field in sys_file_reference

java - 尝试(但失败)为 H2 数据库创建用户函数

java - 查询中的 SQL 变量导致意外的 SQL 语法错误

php - 如果列中的所有行都为 true,则返回 true