根据列中的值按列动态排序
Dynamic sorting by column depending on value in column
简单明了:是否可以创建一个系统动态排序,根据列里面的值,查询会查询。
查询是这样的:
SELECT id, name, sortbycolumn FROM table
WHERE id = :in_id
UNION
SELECT id, name, null sortbycolumn FROM table
WHERE id = :in_id
ORDER BY -- This part I simply don't know how to write. I have tried case and decode...
来回答。我终于找到了解决方案。这很简单,当我阅读其他答案时,我很困惑为什么它对我不起作用。显然,当使用 case when.
时,列的索引将不起作用
最后,我将带有联合的整个查询放到一个子查询中,解决方案是:
SELECT * FROM(
SELECT id, name, sortbycolumn FROM table
WHERE id = :in_id
UNION
SELECT id, name, null sortbycolumn FROM table
WHERE id = :in_id
)
ORDER BY
case when sortbycolumn = 1 THEN id,
case when sortbycolumn = 2 then name
else id end
简单明了:是否可以创建一个系统动态排序,根据列里面的值,查询会查询。
查询是这样的:
SELECT id, name, sortbycolumn FROM table
WHERE id = :in_id
UNION
SELECT id, name, null sortbycolumn FROM table
WHERE id = :in_id
ORDER BY -- This part I simply don't know how to write. I have tried case and decode...
来回答。我终于找到了解决方案。这很简单,当我阅读其他答案时,我很困惑为什么它对我不起作用。显然,当使用 case when.
时,列的索引将不起作用最后,我将带有联合的整个查询放到一个子查询中,解决方案是:
SELECT * FROM(
SELECT id, name, sortbycolumn FROM table
WHERE id = :in_id
UNION
SELECT id, name, null sortbycolumn FROM table
WHERE id = :in_id
)
ORDER BY
case when sortbycolumn = 1 THEN id,
case when sortbycolumn = 2 then name
else id end