什麼是你想要的默認值?表中的第一個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
說明:
Basicly這查詢提取所有你計數的行獲取並將其與默認行組合。他們每個都得到一個prio值,你在做RAND()
之前先訂購它們。剩下的事情就是你想如何存儲你的默認行。
嗯,這似乎是要走向我所需要的 – nico 2012-04-11 07:20:34
我已經添加了一些解釋。讓我知道你是否需要更多的例子。 – 2012-04-11 07:25:54
我會做一些測試,謝謝! – nico 2012-04-11 07:27:57