Jump to content

[SOLVED] How to display all from one table but only if they dont exsist in another


esport

Recommended Posts

Hi Guys,

Having troubles trying to produce a query. I want to display all users form the user table, but only display the users that are not assigned a project in the project table. How do I do this? I have tried using LEFT JOINS, but I think I may need to do inner queries.

 

user table

user_id

name

1

Dan

2

Joe

3

Ash

4

Ben

 

project table

user_id

project_id

1

2

3

2

 

So in this example the results should only display Joe and Ben

 

Thanks in advance for any help.

 

d

Link to comment
Share on other sites

Thanks for the quick response.

 

Im assuming where you have

 

USING (user_id)

 

the user_id is from the user table or the project table? Do I need to add a prefix?

 

I didnt seem to work. Also if I just want to check a certain project I just add in

 

WHERE p.project_id = $project_id

Link to comment
Share on other sites

this is what i have got so far using an inner query. It doesnt seem to work

 

SELECT e.name, e.surname, e.id as employee_id 
			  					  FROM users u, projects p
								  WHERE u.id=p.employee_id AND u.id NOT IN
								  (SELECT p.employee_id FROM prjects p WHERE p.project_id=$project_id)

Link to comment
Share on other sites

Im not sure if this will make a difference but the coloumn name in the user table is 'id' not 'user_id' but 'id' is a reference in project table.

 

Yes, it makes a difference

 

SELECT u.name

FROM user u

LEFT JOIN project p ON u.id = p.user_id

WHERE p.user_id IS NULL

 

Joins are usually faster than subqueries

 

Link to comment
Share on other sites

Thanks im getting somewhere now. However when I add another clause it doesn't produce any results. This is what I am now using.

 

SELECT u.name, u.surname, u.id, p.project_id
FROM users u 
LEFT JOIN projects p ON u.id=p.user_id
WHERE p.project_id=$project_id AND p.user_id IS NULL


 

it doesn't like this

 

p.project_id=$project_id

 

thanks

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.