简体   繁体   English

SELECT 最后一行,但前提是列值是预期值

[英]SELECT last row, but only if column value is the expected one

My Table我的桌子

---------------------
id | userid | name
---------------------
0     1       John
1     2       Ellen
2     1       Peter
---------------------

This table shows, that John has changed his name to Peter (same userid - same person) as id =2 is newer record than id= 0此表显示, John已将他的名字更改为Peter (相同的userid - 同一个人),因为id =2 比 id= 0更新记录

Now... I may want to check whether John is the last name of userid =1.现在...我可能想检查John是否是userid =1 的姓氏。 I need to SELECT id of the LAST row WHERE userid =1, but only if name = John .我需要最后一行的 SELECT id WHERE userid = 1,但前提是name = John And since name in the last row with userid =1 is not John in this particular case, NULL should be returned.由于在这种特殊情况下, userid = 1 的最后一行中的name不是John ,因此应该返回 NULL。 How do I do that?我怎么做? With single SQL command.使用单个 SQL 命令。 Thanks谢谢

I am using Sqlite3 by the way, some advanced MySQL stuff may not work in my case顺便说一句,我正在使用 Sqlite3,一些高级 MySQL 的东西可能不适用于我的情况

Well, one method is to use order by and limit the results to one row:好吧,一种方法是使用order by并将结果限制为一行:

select (case when name = 'John' then name end)
from t
where userid = 1
order by id desc
fetch first 1 row only;

This uses the fetch first clause because it is Standard SQL.这使用了fetch first子句,因为它是标准 SQL。 Your database might have another method.您的数据库可能有另一种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM