I have three tables:
computers, which has columns for id, serial number, make, model, etc users, which has columns for id, real name computer_usage, which has columns id, computer_id, user_id, start_date, end_date
The database records all computers that we have, our users, and who used what computer when.
I want to run a query that selects all computers that do not have a current user.
This would be:
There is a computer_id that doesn't exist at all within computer_usage or There is a computer_id that does exist within computer_usage that has an end_date ofWhat is the best way of selecting those records?
Try this:
SELECT *
FROM computers
WHERE id NOT IN
(SELECT computer_id
FROM computer_usage
WHERE end_date is NULL)
The subquery shows you all computers that are currently in use (a record exists, so we assume it has a start_date, but no end_date has been assigned).
I'm assuming here that the end_date doesn't get populated until the "usage" is complete. If that isn't correct (if the end dates are pre-assigned, for example), then just do:
SELECT *
FROM computers
WHERE id NOT IN
(SELECT computer_id
FROM computer_usage
WHERE start_date < getDate()
AND end_date > getDate())
The subquery still shows all computers that are currently "on assignment". Just find all computers not in that group. (Note that I've used "getDate", which is a MS SQL function. I think the mysql equivalent is something having to do with TIMESTAMP.)
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.