合并查詢結果
将兩次或者兩次以上的結果合并在一起
要求: 兩次查詢的列數一緻
推薦,查詢每一列,相對應的列類型是一樣的
多次sql語句 取出 的列名可以不一緻,此時以取第一個sql 的列名為準。
如果不同的語句中取出的行 有每個列的值都相同,那麼相同的行将被合并成一行(去重複)
如果不想去重複union加上 all
建立表格
create table ta
(id char(1) default null,
num int not null default 0
) engine=InnoDB charset=utf8;
insert into ta
(id,num)
values
('a',10),
('b',20),
('c',30),
('d',40);
create table tb
insert into tb
('a',50),
('b',60),
('c',70),
('d',80);
1 合并 兩張表格
2 合并兩張表單 把相同id下的數值sum求和
發現問題
使用聚合 函數時 不許有空格
Sum(num)
Sum (num)
将會把 sum 識别為 表 報該資料庫下不存在該表單錯誤
Error 1630(42000)
注意:如果子句裡 有 order by | limit 需要 union 兩邊加小括号
例如
(select good_id,cat_id,goods_name,shop_price from goods _id =where cat_id = 4 order by
shop_price desc )union (select good_id,cat_id,goods_name,shop_price from goods _id =where
cat_id = 5 order by shop_price desc);
但是 容易有誤
解決方案
1 order by 盡量放在最後使用 即歲最終合并後的結果 進行排序
(select good_id,cat_id,goods_name,shop_price from goods _id =where cat_id = 4 )union
(select good_id,cat_id,goods_name,shop_price from goods _id =where cat_id = 5 order by
shop_price desc;
2 每個子語句 加上limit