你想要的默认值是多少?表中的第一个 id?
SELECT id, text
FROM ( SELECT id, categori, active, text, 0 AS prio
FROM table WHERE category = [category id] AND active = 1
UNION ALL
SELECT id, categori, active, text, 1
FROM table
ORDER BY id ASC
LIMIT 1) AS h
ORDER BY prio, RAND()
LIMIT 1
如果您希望获得某个默认值,请添加一个名为的 ENUM 列default('TRUE', 'FALSE')
:
SELECT id, text
FROM ( SELECT id, categori, active, text, 0 AS prio
FROM table WHERE category = [category id] AND active = 1 AND default = 'FALSE'
UNION ALL
SELECT id, categori, active, text, 1
FROM table
WHERE category = [category id] AND default = 'TRUE'
ORDER BY id ASC
LIMIT 1) AS h
ORDER BY prio, RAND()
LIMIT 1
更简单的一个:
SELECT id, text
FROM table
WHERE category = [category id] AND (active = 1 OR default = 'TRUE')
ORDER BY (default = 'FALSE') DESC, RAND()
LIMIT 1
说明:
基本上,这个查询会获取您指望获取的所有行,并将其与默认行结合起来。他们每个都有一个优先价值,你在做之前订购它们RAND()
。剩下的就是您希望如何存储默认行。