“测试” 表结构
我要检查表“测试” 中是否有 itemID ='123'和 value ='456'的结果以及它是否是最后添加的结果ORDER BY id DESC ,我错过了这段代码:
SELECT * FROM Test WHERE itemID = '123' AND value= '456' ORDER BY id DESC LIMIT 1
有人可以帮忙吗?
答案 0 :(得分:2)
检查表
Test
中是否有itemID = '123'
和value = '456'
的结果,以及它是否是最后添加的结果ORDER BY id DESC
您的要求可以按如下方式翻译:
select *
from test t
where itemID = 123 and value = 456
and not exists (
select 1
from test t1
where t1.id > t.id
)
NOT EXISTS
条件确保选择的记录是最新的id
方式。
如果不满足要求,查询将返回一个空结果集。
表达它的另一种方法是使用相关的子查询来获取最新的ID:
select *
from test t
where
itemID = 123
and value = 456
and id = (select max(id) from test t)
答案 1 :(得分:1)
在where子句中使用Sub查询,即可找到它。
SELECT t.* FROM `Test` as t WHERE `itemID` = 123 AND `value` = 456 AND `id` =(SELECT max(`id`) FROM Test);
答案 2 :(得分:0)
SELECT (SELECT value
FROM Test
WHERE itemID = '123'
ORDER BY id DESC LIMIT 1) = '456' AS it_matches;
结果将是以下可能性之一: