这是我的实际查询:
SELECT DISTINCT eventi.img AS img, posizione AS pos
FROM eventi
WHERE homepage =1
UNION
SELECT DISTINCT prodotti.img, prodotti.posizione
FROM prodotti
WHERE homepage =1
ORDER BY pos ASC
它会返回像" 1,1,2,2和#34; 。我希望它按字段返回位置,例如"事件位置1,2 - >然后产品位置1,2" 。现在它是混合事件和产品的位置......
答案 0 :(得分:2)
你可以这样做:
SELECT t.img,t.pos FROM (
SELECT DISTINCT 1 as order_col, eventi.img AS img, posizione AS pos
FROM eventi
WHERE homepage =1
UNION
SELECT DISTINCT 2 , prodotti.img, prodotti.posizione
FROM prodotti
WHERE homepage =1 ) t
ORDER BY t.order_col,t.pos
如果您不关心选择order_col
,那么您可以避免子选择并在内部下订单。
答案 1 :(得分:0)
根据docs,你有一个联盟,你需要采取额外的步骤来确保联盟的最终查询中的order by
子句适用于所有查询,而不是只是最后一个问题:
SELECT ...
UNION
SELECT ... ORDER <--order final query only
v.s
(SELECT ...)
UNION
(SELECT ...) ORDER <--order all queries as a single set
请注意额外的()
。