請問
SELECT ShopName, CommentMagnitude+CommentTaste+CommentEnvironment+CommentService
FROM shop, shopcity, shopdish
WHERE shop.shopID=shopcity.shopID
AND shop.shopID=shopdish.shopID
AND shopdish.dishID='DS_0010'
AND shopcity.cityID='CT_0001'
ORDER BY CommentMagnitude+CommentTaste+CommentEnvironment+CommentService DESC LIMIT 0,20
及
SELECT ShopName, CommentMagnitude+CommentTaste+CommentEnvironment+CommentService
FROM shop, shopcity, shopdish
WHERE shop.shopID=shopcity.shopID
AND shop.shopID=shopdish.shopID
AND shopdish.dishID='DS_0010'
AND shopcity.cityID='CT_0001'
ORDER BY CommentMagnitude+CommentTaste+CommentEnvironment+CommentService ASC LIMIT 0,20
的結果用UNION是否可以合併起來
如果寫在同一句SQL(就是你的及
字,直接改成union all
的話),答案是不行。
在相同一個query之下,更白話的說,在相同一個分號(;)之內、一句SQL底下,order by和limit,是針對【整句SQL的資料】去做order by和limit,換句話說,你不可能一句SQL裡面出現了兩次order by和limit。
例如以下這個語法:
DROP TABLE IF EXISTS ithelp_20181210
;
CREATE TABLE ithelp_20181210 as
select * from ithelp_20181210_1 union all
select * from ithelp_20181210_2
;
select * from ithelp_20181210
你注意分號(;)的位置,2個分號,把3句SQL給分開,換句話說,
select * from ithelp_20181210_1 union all
select * from ithelp_20181210_2
這是同一句SQL。
同一句SQL裡面,order by和limit,只能發生在select完的資料之後,例如:
針對的是上面兩行select,做order by和limit。
但下面這就會出錯,而且提示給你的錯誤,你也會不知道自己哪裡出了錯:
原因就是你這指令是,先針對第一句select做order by和limit,再針對第二句select做order by和limit,接著把兩句union起來,這件事實際有三個動作,無法發生在【同一句SQL】底下。
然而,你可以透過子句的方式,先把要union的資料做完後select,就可以union囉~ 如下:
SELECT ShopName,AA
FROM
(
SELECT ShopName, CommentMagnitude+CommentTaste+CommentEnvironment+CommentService AS 'AA'
FROM shop, shopcity, shopdish
WHERE shop.shopID=shopcity.shopID
AND shop.shopID=shopdish.shopID
AND shopdish.dishID='DS_0010'
AND shopcity.cityID='CT_0001'
ORDER BY CommentMagnitude+CommentTaste+CommentEnvironment+CommentService DESC LIMIT 0,20
) AS XTABLE
UNION
SELECT ShopName,AA
FROM
(
SELECT ShopName, CommentMagnitude+CommentTaste+CommentEnvironment+CommentService AS 'AA'
FROM shop, shopcity, shopdish
WHERE shop.shopID=shopcity.shopID
AND shop.shopID=shopdish.shopID
AND shopdish.dishID='DS_0010'
AND shopcity.cityID='CT_0001'
ORDER BY CommentMagnitude+CommentTaste+CommentEnvironment+CommentService ASC LIMIT 0,20
) AS YTABLE