简体   繁体   中英

MySQL query and compare two different tables

I'm very new to SQL queries, so forgive me if this is a really easy question.

I have 2 database tables HWC and collection , HWC.id is referenced in collection.col

HWC
- id (PRIMARY)
- stuff
- more stuff
- lots more stuff
- Year

collection
- id (PRIMARY)
- userId
- col

Question:

I want to query the collection table for a specific user to see what entries from HWC they are missing.

I don't even know where to start logically, I don't expect anyone to build the query for me, but pointing me in the correct direction would be very much appreciated.

You want items from the collect that the user is missing . This suggests a left outer join . In particular, you want to keep everything in the HWC table and find those things that are missing:

select hwc.*
from hwc left join
     collection c
     on hwc.id = c.col
where hwc.id is null and c.user_id = @UserId;

When learning SQL, students often learn this syntax:

select hwc.*
from hwc
where hwc.id not in (select c.col from collection c where c.user_id = @UserId);

This is perfectly good SQL. Some databases don't do a great job optimizing not in . And, it can behave unexpectedly when c.col is NULL . For these reasons, this is often rewritten as a not exists query:

select hwc.*
from hwc
where not exists (select 1
                  from collection c
                  where c.col = hwc.id and c.user_id = @UserId
                 );

I offer you these different alternatives because you are learning SQL. It is worth learning how all three work. In the future, you should find each of these mechanisms ( left join , not in , and not exists ) useful.

It sounds like you mean SQL JOINS.

SQL Joins Tutorial:

Lets say you want to Query your collection like so:

SELECT collection.userId, HWC.stuff
FROM collection 
INNER JOIN HWC ON collection.col = HWC.id

This will pick userId from collection, and stuff from HWC, where these ID's have relations.

Hope I helped, good luck!

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