MySQL ORDER BY 第一个字段然后第二个字段
MySQL ORDER BY first field then second field
这是我的实际查询:
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
它 returns 像 "1,1,2,2" 这样的位置。我想要 returns 按字段定位,例如 "event position 1,2 -> then products position 1,2" 。现在它混合了事件和产品位置...
根据 docs,你有一个联合,你需要采取额外的步骤来确保联合的最终查询中的 order by
子句适用于所有查询,而不仅仅是最后的查询:
SELECT ...
UNION
SELECT ... ORDER <--order final query only
v.s
(SELECT ...)
UNION
(SELECT ...) ORDER <--order all queries as a single set
注意额外的 ()
.
你可以这样做:
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
如果您不关心 selecting order_col
那么您可以避免使用 sub select 并在里面下订单。
这是我的实际查询:
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
它 returns 像 "1,1,2,2" 这样的位置。我想要 returns 按字段定位,例如 "event position 1,2 -> then products position 1,2" 。现在它混合了事件和产品位置...
根据 docs,你有一个联合,你需要采取额外的步骤来确保联合的最终查询中的 order by
子句适用于所有查询,而不仅仅是最后的查询:
SELECT ...
UNION
SELECT ... ORDER <--order final query only
v.s
(SELECT ...)
UNION
(SELECT ...) ORDER <--order all queries as a single set
注意额外的 ()
.
你可以这样做:
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
如果您不关心 selecting order_col
那么您可以避免使用 sub select 并在里面下订单。