简体   繁体   中英

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?

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. 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? (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:

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)

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子句信息

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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