-- 刪除已存在的表 one, two, three,如果存在的話DROPTABLEIFEXISTS one;DROPTABLEIFEXISTS two;DROPTABLEIFEXISTS three;-- 創建表 one,包含 one_id(主鍵),two_id 和 one_name 列createtableone ( one_id int unsigned primary keynot null auto_increment, two_id int unsigned not null, one_name varchar(10) null);-- 創建表 two,包含 two_id(主鍵),three_id 和 two_name 列createtabletwo ( two_id int unsigned primary keynot null auto_increment, three_id int unsigned not null, two_name varchar(10) not null);-- 創建表 three,包含 three_id 和 three_name 列createtablethree ( three_id int unsigned, three_name varchar(10) not null);-- 向表 one 插入數據insert into one(two_id, one_name) VALUES (1,'id_1') ,(2,'id_2'),(3,'id_3'),(4,'id_1');-- 向表 two 插入數據insert into two(three_id, two_name) VALUES (1,'id_1') ,(2,'id_2'),(3,'id_3'),(4,'id_1');-- 向表 three 插入數據insert into three(three_name) VALUES ('id_1') ,('id_2'),('id_3'),('id_1');# 以下可以自行加上 EXPLAIN 去查看解釋內容-- 查詢表 one(o)、two(t)、three(r)的所有列,通過條件關聯它們-- 具體條件:表 one 中的 two_id 等於表 two 中的 two_id,表 two 中的 three_id 等於表 three 中的 three_idSELECT*FROM one o, two t, three r WHERE o.two_id = t.two_id AND t.three_id = r.three_id;-- 查詢表 one(o)中的所有列,其中條件為 o.two_id 等於子查詢的結果-- 子查詢:從表 two(t)中選擇 t.two_id,其中 t.three_id 等於子查詢的結果-- 子查詢:從表 three(r)中選擇 r.three_id,其中 r.three_name 等於 '我是第三表2'SELECT * FROM one o WHERE o.two_id = (SELECT t.two_id FROM two t WHERE t.three_id = (SELECT r.three_id FROM three r WHERE r.three_name='我是第三表2'));
-- 查詢表 one(o)中的所有列,其中條件為 o.two_id 等於子查詢的結果,並且 o.one_id 在表 one 中有與 o.one_name='我是第一表2' 相關聯的行SELECT * FROM one o WHERE o.two_id = (SELECT t.two_id FROM two t WHERE t.three_id = (SELECT r.three_id FROM three r WHERE r.three_name='我是第三表2')) AND o.one_id IN (SELECT one_id FROM one WHERE o.one_name='我是第一表2');
-- 查詢表 two(t)中的 two_name 列和一個子查詢的結果(one.one_id),該子查詢返回表 one(one)中的 one_id 列-- 使用 UNION 運算符將兩個查詢的結果合併-- 第一個查詢選擇表 two 中 two_id 和 two_name 列,其中 two_name 為空字符串('')-- 第二個查詢選擇表 three(r)中的 three_name 列和 three_id 列SELECT t.two_name, (SELECT one.one_id FROM one) o FROM (SELECT two_id, two_name FROM two WHERE two_name ='') t UNION (SELECT r.three_name, r.three_id FROM three r);
-- 查詢表 one 中 one_id=1 的所有列SELECT*FROM one WHERE one_id=1;-- 查詢表 one(o)中的 one_name 列,同時關聯表 two(t)以匹配 o.one_id = t.two_idSELECT o.one_name FROM one o, two t WHERE o.one_id = t.two_id;-- 查詢表 one(o)中的 one_id 列,其中 o.one_name = 'id_1'SELECT o.one_id FROM one o WHERE o.one_name ='id_1';-- 查詢表 one(o)中的 one_id 列,其中 o.one_name = 'id_1' 或 o.one_name 為空(NULL)-- 無法獲得 type = ref_or_null 的結果SELECT o.one_id FROM one o WHERE o.one_name ='id_1'OR o.one_name ISNULL;-- 查詢表 one(o)中的所有列,其中 o.one_id > 1 且 o.one_name = 'xin'SELECT*FROM one o WHERE o.one_id >1AND o.one_name ='xin';-- 查詢表 three 中 three_id 介於 2 和 3 之間的所有列SELECT*FROM three WHERE three_id BETWEEN2AND3;-- 查詢表 two 中的 two_id 列SELECT two_id FROM two;-- 查詢表 two 中的所有列SELECT*FROM two;