如何合并 MySQL 结果?
若要合并,请使用简单的 join。以下是语法 –
select aliasName1.yourColumnName1, aliasName1.yourColumnName2, . . .N aliasName2.yourColumnName1 from yourTableName1 aliasName1 . . . N join yourTableName2 aliasName2 on yourCondition;
我们创建一个表 –
mysql> create table demo8 −> ( −> id int, −> name varchar(20) −> ); Query OK, 0 rows affected (1.77 sec)
使用 insert 命令,将一些记录插入到表中 –
mysql> insert into demo8 values(100,'John'); Query OK, 1 row affected (0.09 sec) mysql> insert into demo8 values(101,'Mike'); Query OK, 1 row affected (0.16 sec) mysql> insert into demo8 values(102,'Bob'); Query OK, 1 row affected (0.15 sec)
使用 select 语句从表中显示记录 –
mysql> select *from demo8;
这会产生以下输出 –
+------+------+ | id | name | +------+------+ | 100 | John | | 101 | Mike | | 102 | Bob | +------+------+ 3 rows in set (0.00 sec)
下面是创建第二个表的查询 –
mysql> create table demo9 −> ( −> id int, −> age int −> ); Query OK, 0 rows affected (1.90 sec)
使用 insert 命令,将一些记录插入到表中 –
mysql> insert into demo9 values(100,27); Query OK, 1 row affected (0.09 sec) mysql> insert into demo9 values(101,24); Query OK, 1 row affected (0.12 sec) mysql> insert into demo9 values(102,28); Query OK, 1 row affected (0.29 sec)
使用 select 语句从表中显示记录 –
mysql> select *from demo9;
这会产生以下输出 –
+------+------+ | id | age | +------+------+ | 100 | 27 | | 101 | 24 | | 102 | 28 | +------+------+ 3 rows in set (0.00 sec)
以下是合并结果的查询 –
mysql> select tbl1.id,tbl1.name,tbl2.age −> from demo8 tbl1 −> join −> demo9 tbl2 −> on tbl1.id=tbl2.id;
这会产生以下输出 –
+------+------+------+ | id | name | age | +------+------+------+ | 100 | John | 27 | | 101 | Mike | 24 | | 102 | Bob | 28 | +------+------+------+ 3 rows in set (0.00 sec)
广告