Py学习  »  DATABASE

MySQL:首先查找特定值,然后获取第二个值

nieburr • 4 年前 • 755 次点击  

到目前为止我的代码

SELECT * FROM gp 
WHERE status IN ('priority', NULL)  
   AND (status='priority' OR EXISTS(SELECT * FROM gp WHERE status IS NULL)) 
LIMIT 1

我正试着第一排 status = 'priority' 如果存在,或者得到第一行 status = NULL . 状态也可能有其他值,但我只想得到 priority NULL .

到目前为止,我的代码所做的是返回 状态='优先级' 当它们存在的时候,却什么也没有回报 存在。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/53192
 
755 次点击  
文章 [ 1 ]  |  最新文章 4 年前
Nick
Reply   •   1 楼
Nick    4 年前

你不能用 NULL 在一个 IN 表达式,所以您需要更改 WHERE

WHERE status = 'priority' OR status IS NULL

您可以删除 哪里

ORDER BY status = 'priority` DESC

这将放置 status = 'priority' 领先于那些 status 属于

所以你的问题就变成了:

SELECT * FROM gp 
WHERE status = 'priority' OR status IS NULL
ORDER BY status = 'priority` DESC
LIMIT 1

注意,要获得“第一”行 您需要一个ordering列(SQL表是无序的,因此没有ordering列“first”就没有意义),您可以将其添加到 ORDER BY 条款:

SELECT * FROM gp 
WHERE status = 'priority' OR status IS NULL
ORDER BY status = 'priority` DESC, id ASC
LIMIT 1