How to optimize the state correlation of sql message table?

the structure of the table is as follows:
clipboard.png

the unread message I am implementing now is:

SELECT
    `n`.`id`
FROM
    `message` AS `m`
WHERE
    `m`.`id` NOT IN (
        SELECT
            `m_s`.`message_id`
        FROM
            `message_status` AS `m_s`
        WHERE
            `m`.`id` = `n_s`.`message_id`
    );

this kind of implementation statement, the subquery can use all, but the main query cannot use the index, is there any good optimization method under MySQL?

Note that the message has an one-to-many relationship with the user, and a message corresponds to multiple users.

Mar.15,2021

select m.id
from message m left join (select distinct message_id from message_status) s on m.id = s.message_id 
where s.message_id is null

this problem is best solved from a design perspective, marking the message table after reading the message.

in addition, if you use subqueries, it may be more efficient to use not exists.


it is unscientific for you to associate fields like this to judge whether a message has been read. It will be very uncomfortable if the amount of data increases later

.

generally, the message table has a status field to distinguish between them, for example:

-
| Id | number |
-
| State | message status: 1 unread 2 already Read |
-

Association or messageId with message table Id

but if you query unread messages, that's it

SELECT * FROM [message] WHERE State=1

isn't it beautiful!

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e5955b-45501.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e5955b-45501.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?