mysql子句`

guykilcj  于 2021-06-25  发布在  Mysql
关注(0)|答案(3)|浏览(251)

我正在想办法,但根本没有解决办法。我的问题:

SELECT * FROM table
WHERE owner = 'user'
AND (
    CASE WHEN status = 'NEW'
    THEN status = 'NEW'
    ELSE status IN ('CB','NA','NI','GC','FC')
    END
)
ORDER BY RAND() DESC
LIMIT 1;

我想实现的是显示所有记录 statusNEW 在一个 Random order 受限于 one row 没有记录的时候 NEW 对于用户,查询需要显示另一个 statuses .
谢谢您。

cedebl8k

cedebl8k1#

SELECT * FROM table
    WHERE owner = 'user'
      AND status IN ('NEW', 'CB','NA','NI','GC','FC')
    ORDER BY status = 'NEW' DESC,
             RAND() DESC
LIMIT 1;

将给你总共1行,给你一个随机的'新'的优惠。如果没有“新”行,则随机选择其他行。
(请澄清您的问题并提供示例输出。)

vybvopom

vybvopom2#

SELECT * FROM Table
WHERE owner = 'user'
AND (CASE WHEN (SELECT COUNT(*) FROM Table WHERE status = 'NEW') >= 1 THEN
                status = 'NEW'
     ELSE status IN ('CB','NA','NI','GC','FC')
     END)
ORDER BY RAND() DESC
LIMIT 1;

演示
http://sqlfiddle.com/#!9月9日B1C8/1

yruzcnhs

yruzcnhs3#

我想,你可以

SELECT * FROM table
WHERE owner = 'user'
AND (
   CASE WHEN status = 'NEW'
   THEN status = 'NEW'
   ELSE status IN ('CB','NA','NI','GC','FC')
   END
)
ORDER BY RAND() DESC
LIMIT 1;

SELECT * FROM table
WHERE owner = 'user' AND status IN ('NEW','CB','NA','NI','GC','FC')
GROUP By some_id
ORDER BY RAND() DESC
LIMIT 1;

相关问题