而不是做你想做的事,只需选择你需要的唯一行。在前端代码中,在 key=>value 结构中存储每个唯一行一次,其中 key 是项目 ID,value 是您需要的有关该项目的任何数据。
一旦你有了它,你就可以使用前端逻辑以所需的顺序输出它们,包括重复。这将减少您尝试选择的冗余数据量。
例如,这不是可用的代码 - 所需的确切语法取决于您的脚本语言
-- setup a display order
displayOrder= [1,2,1,3];
-- select data from database, order doesn't matter here
SELECT id,date
FROM items
WHERE id IN (displayOrder);
-- cache the results in a key=> value array
arrCachedRows = {};
for (.... each db row returned ...) {
arrCachedRows[id] = date;
}
-- Now output in desired order
for (listIndex in displayOrder) {
-- Make sure the index is cached
if (listIndex exists in arrCachedRow) {
echo arrCachedRows[listIndex ];
}
}
如果你必须不顾我的警告而坚持使用 UNION
如果您违反上述建议,并且绝对必须按该顺序将它们放回 1 个查询中,则添加一个额外的行,该行将强制执行该行顺序。请参阅下面的查询,其中我使用变量 @subIndex 将递增值添加为 subIndex。这反过来又可以让您重新排序,它将按照请求的顺序。
SELECT
i.*
FROM (
SELECT @subIndex:=@subIndex+1 AS subIndex, id, date FROM items where id = 1
UNION
SELECT @subIndex:=@subIndex+1 AS subIndex, id, date FROM items where id = 2
UNION
SELECT @subIndex:=@subIndex+1 AS subIndex, id, date FROM items where id = 1
UNION
SELECT @subIndex:=@subIndex+1 AS subIndex, id, date FROM items where id = 3
) AS i,(SELECT @subIndex:=0) v
ORDER BY i.subIndex
或者一个稍微干净的版本,将项目选择保留到外部并隐藏子索引
SELECT
items.*
FROM items
-- initialise variable
INNER JOIN (SELECT @subIndex:=0) v
-- create a meta-table with the ids desired in the order desired
INNER JOIN (
SELECT @subIndex:=@subIndex+1 AS subIndex, 1 AS id
UNION
SELECT @subIndex:=@subIndex+1 AS subIndex, 2 AS id
UNION
SELECT @subIndex:=@subIndex+1 AS subIndex, 1 AS id
UNION
SELECT @subIndex:=@subIndex+1 AS subIndex, 3 AS id
) AS i
ON i.id = items.id
-- order by the subindex from i
ORDER BY i.`subIndex` ASC