简体   繁体   English

我是否需要在'IN(SELECT MAX(id)')子查询中重复WHERE子句?

[英]Do I need to repeat the WHERE clause in a 'IN (SELECT MAX(id)' subquery?

Do I need to specify the WHERE clause inside this subquery as well? 我是否还需要在此子查询中指定WHERE子句?

SELECT title, message FROM messages WHERE sender = '.$myid.' AND read != 1 AND id
IN (SELECT MAX(id) FROM messages GROUP BY conversation) ORDER BY id DESC

It seems like the result is the same with/without repeating the WHERE clause, but it's hard to test without having a lot of different users and messages. 似乎有/没有重复WHERE子句的结果是相同的,但是如果没有很多不同的用户和消息,很难进行测试。 So I need to be more sure. 所以我需要更加确定。

Is it necessary to repeat the WHERE clause like this 🡫, or is the IN subquery already narrowed down by the first WHERE clause? 是否有必要像这样重复WHERE子句,还是第一个WHERE子句已经缩小了IN子查询? (I assume the latter but I'm not sure). (我假设是后者,但不确定)。

SELECT title, message FROM messages WHERE sender = '.$myid.' AND read != 1 AND id
IN (SELECT MAX(id) FROM messages WHERE sender = '.$myid.' AND read != 1 GROUP BY conversation) ORDER BY id DESC

Both are simplified examples from my code. 两者都是我代码中的简化示例。 I hope my question makes sense. 我希望我的问题有道理。

The where in the outer query is redundant as in your inner query (subquery) you are requesting specific ids using the constraint you want so basically when you have something like this: 像内部查询(子查询)一样,外部查询中的where是多余的,您使用所需的约束来请求特定的ID,基本上,当您遇到类似这样的情况时:

SELECT title, message FROM messages WHERE id IN (SELECT MAX(id) FROM messages WHERE
sender = '.$myid.' AND read != 1 GROUP BY conversation) ORDER BY id DESC

it would be like you have gathered the ids first & then requested the specific records similar to: select x from y where id in(1, 2, 3) 好像您先收集了ID,然后请求了特定的记录,类似于: select x from y where id in(1, 2, 3)

For this same exact query it would be like running the following 2 queries: 对于相同的确切查询,就像运行以下两个查询:

Query 1: SELECT MAX(id) FROM messages WHERE sender = '.$myid.' AND read != 1 GROUP BY conversation

Result: 1, 2, 3

The second query is: 第二个查询是:

Query 2: SELECT title, message FROM messages WHERE id IN (1, 2, 3) ORDER BY id DESC

就解析的参数而言,子查询select与第一个查询完全分开,因此您将不得不再次输入where子句信息

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

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