select * from a,b探討
今天看同事代碼里使用了select * from a,b where a.id=b.id
,而我平時都是使用select * from a inner join b where a.id=b.id
,於是查了下,發現:
1)單純的select * from a,b
是笛卡爾乘積
2)select * from a,b where a.id=b.id
相當於inner join
#### 驗證
1)創建兩張表
create table userinfo(
uid int(10) not null default 0,
report_id int(10) not null default 0,
primary key(uid)
) engine=innodb default charset=utf8;
create table report(
report_id int(10) not null default 0,
description varchar(255) default '',
primary key(report_id)
) engine=innodb default charset=utf8;
2)插入測試數據
insert into userinfo values(1,1),(2,1),(3,2),(4,6);
insert into report values(1,'第一條'),(2,'第二條'),(3,'第三條');
mysql> select * from userinfo;
+-----+-----------+
| uid | report_id |
+-----+-----------+
| 1 | 1 |
| 2 | 1 |
| 3 | 2 |
| 4 | 6 |
+-----+-----------+
4 rows in set (0.00 sec)
mysql> select * from report;
+-----------+-------------+
| report_id | description |
+-----------+-------------+
| 1 | 第一條 |
| 2 | 第二條 |
| 3 | 第三條 |
+-----------+-------------+
3 rows in set (0.00 sec)
3)驗證
單獨的select * from a,b
select * from userinfo,report
結果
mysql> select * from userinfo,report;
+-----+-----------+-----------+-------------+
| uid | report_id | report_id | description |
+-----+-----------+-----------+-------------+
| 1 | 1 | 1 | 第一條 |
| 1 | 1 | 2 | 第二條 |
| 1 | 1 | 3 | 第三條 |
| 2 | 1 | 1 | 第一條 |
| 2 | 1 | 2 | 第二條 |
| 2 | 1 | 3 | 第三條 |
| 3 | 2 | 1 | 第一條 |
| 3 | 2 | 2 | 第二條 |
| 3 | 2 | 3 | 第三條 |
| 4 | 6 | 1 | 第一條 |
| 4 | 6 | 2 | 第二條 |
| 4 | 6 | 3 | 第三條 |
+-----+-----------+-----------+-------------+
12 rows in set (0.00 sec)
可見select * from a,b
是笛卡兒積
再來驗證select * from a,b where a.id=b.id
mysql> select * from userinfo,report where userinfo.report_id=report.report_id;
+-----+-----------+-----------+-------------+
| uid | report_id | report_id | description |
+-----+-----------+-----------+-------------+
| 1 | 1 | 1 | 第一條 |
| 2 | 1 | 1 | 第一條 |
| 3 | 2 | 2 | 第二條 |
+-----+-----------+-----------+-------------+
3 rows in set (0.00 sec)
inner join
mysql> select * from userinfo inner join report where userinfo.report_id=report.report_id;
+-----+-----------+-----------+-------------+
| uid | report_id | report_id | description |
+-----+-----------+-----------+-------------+
| 1 | 1 | 1 | 第一條 |
| 2 | 1 | 1 | 第一條 |
| 3 | 2 | 2 | 第二條 |
+-----+-----------+-----------+-------------+
3 rows in set (0.00 sec)
mysql> select * from userinfo inner join report on userinfo.report_id=report.report_id;
+-----+-----------+-----------+-------------+
| uid | report_id | report_id | description |
+-----+-----------+-----------+-------------+
| 1 | 1 | 1 | 第一條 |
| 2 | 1 | 1 | 第一條 |
| 3 | 2 | 2 | 第二條 |
+-----+-----------+-----------+-------------+
3 rows in set (0.00 sec)
可見是select * from a,b where a.id=b.id
只是把笛卡爾積做了一層過濾,結果與inner join
相同
補充:inner join是先生成一個臨時表,然后使用on條件篩選
注:以上結論只在mysql 5.7驗證過,其他數據庫不一定成立