gpt4 book ai didi

php - mysql自定义排序方式

转载 作者:太空宇宙 更新时间:2023-11-03 12:27:05 25 4
gpt4 key购买 nike

我在 settings 表中有设置顺序,我想用这个选项更改 order by,在下面的 sql 命令中,如果 我想使用这个选项settings 中的 sortable 字段为 1,则 order by 必须为 ORDER BY DATE 如果 sortable 为 2,则 order by 必须为 按 ID 订购。请帮助我获得正确的 sql 命令

数据库:

SELECT 
SQL_CALC_FOUND_ROWS i.* ,
c.title AS category_name,
u.name,
u.family,
s.title AS status_title,
i.thumb_image,
CONCAT( u.name, ' ', u.family ) AS author
FROM contents i
JOIN categories c ON c.id = i.category
JOIN users u ON u.id = i.posted_by
JOIN status_topics s ON s.id = i.t_status
WHERE
i.portal = 0
AND (CASE WHEN post_type = 4
THEN date(NOW()) BETWEEN i.from_dateTime AND i.to_dateTime
ELSE post_type = 1
END)

(select sortable from settings)
(case when sortable = 1 then
ORDER BY topic_date
case when sortable = 2 then
ORDER BY id
case when sortable = 3 then
ORDER BY public
end)

LIMIT 10

最佳答案

注意 根据与 OP 的讨论,答案略有变化。

ORDER BY 放在 CASE 之外,如下所示:

... the first part of the query, then ...
ORDER BY
CASE (SELECT sortable FROM settings)
WHEN 1 THEN topic_date
WHEN 2 THEN id
WHEN 3 THEN public
END
LIMIT 10

请注意,这仅在 (SELECT sortable FROM settings) 返回 one 行时有效。如果它返回多行,则会出现错误。如果它返回零行,则不会出现错误,但不会选择任何排序选项 - 这与说 ORDER BY NULL 相同。

关于php - mysql自定义排序方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17069044/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com