patternsqlMinor
Query between two related tables
Viewed 0 times
tablesqueryrelatedtwobetween
Problem
I have two tables. One of them (user_profile table) has a field named "user_profile_id" and the other one (user_friend table) has two fields named "user_profile1_id" and "user_profile2_id" which are FK to the first table.
I want to check if there are any users in user_profile which are not in user_friend table, neither in user_profile1_id, nor user_profile2_id.
What query should I use?
EDIT:
I want to check if there are any users in user_profile which are not in user_friend table, neither in user_profile1_id, nor user_profile2_id.
What query should I use?
EDIT:
CREATE TABLE user_profile (
--fields
)
CREATE TABLE user_friend (
user_profile1_id INT,
user_profile2_id INT
)Solution
Use a
Here's a link to the various joins
LEFT JOIN and check for null values. Something like:SELECT profile.* FROM user_profile profile
LEFT JOIN user_friend friend1 ON friend1.user_profile1_id = user_profile_id
LEFT JOIN user_friend friend2 ON friend2.user_profile2_id = user_profile_id
WHERE friend1.user_profile1_id IS NULL AND friend2.user_profile2_id IS NULLHere's a link to the various joins
Code Snippets
SELECT profile.* FROM user_profile profile
LEFT JOIN user_friend friend1 ON friend1.user_profile1_id = user_profile_id
LEFT JOIN user_friend friend2 ON friend2.user_profile2_id = user_profile_id
WHERE friend1.user_profile1_id IS NULL AND friend2.user_profile2_id IS NULLContext
StackExchange Database Administrators Q#1427, answer score: 4
Revisions (0)
No revisions yet.