I have a table of user (table users) and a log table (table logs) with serval logs about the user. Now I'm looking for a way to return me a list of user where a specific value in the logs is missing.
Lets have the following example:
table users table logs
---------------- -----------------------------
| id | user | | id | user_id | status |
---------------- -----------------------------
| 1 | user1 | | 1 | 2 | send |
---------------- -----------------------------
| 2 | user2 | | 2 | 1 | send-error |
---------------- -----------------------------
| 3 | user3 | | 3 | 3 | status-x |
---------------- -----------------------------
| 4 | 1 | send |
-----------------------------
| 5 | 3 | send-error |
-----------------------------
The following join returns me a list of all users and there logs:
SELECT u.id, u.name, l.status
FROM users u
LEFT JOIN logs l ON u.id = t.user_id
How can I select only the ones which have not the status 'send'? In this example it should just return id=3, user=user3 .
SELECT u.id, u.name, l.status
FROM users u
LEFT JOIN logs l ON u.id = l.user_id
WHERE NOT EXISTS (SELECT 1 FROM logs g
WHERE u.id = g.user_id
AND g.status = 'send')
Basically, check out NOT EXISTS
for queries like the one you want. If the subquery would return no rows, the NOT EXISTS
condition holds, and the row is returned.
Edit:
If you only wish to see which users do not have a status of "send" in the logs
table:
SELECT u.id, u.name
FROM users u
WHERE NOT EXISTS (SELECT 1 FROM logs l
WHERE u.id = l.user_id
AND l.status = 'send')
This query avoids the need for GROUP BY
just to get one user per row, if that is all you are trying to do.
SELECT u.id, u.user, l.status
FROM users u
LEFT JOIN logs l ON u.id = l.user_id
WHERE l.status not like '%send%'
You are already performing the left join (assuming that you want all users and those log entries where the user ID matches). It's a simple matter then to check the status field for the absence of the word 'send'.
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.