Jump to content

Joining Tables not working as expected


imperium2335

Recommended Posts

Hi,

 

I am trying to get my query to fetch all the records that belong to users that belong to a given branch:

 

$result = mysql_query("SELECT enquiries.*, users.userName
					  FROM enquiries, users
					  WHERE enquiries.enqState = 'New'
					  AND users.branch = '$userBranch'
					  AND enquiries.assignedToT = users.userName
					  ORDER BY enquiries.id DESC
					  ")or die(mysql_error()) ;

 

$userBranch is stored as a session variable, and can be something like 'UK' or 'Spain' etc.

 

For UK branch, there are four users, but the query is only outputting items for two of them :(

 

Link to comment
https://forums.phpfreaks.com/topic/235433-joining-tables-not-working-as-expected/
Share on other sites

Hi,

 

enquiries relates to users through assignedToT, which contains the same value if the enquiry belongs to a given user, e.g. WHERE enquiries.assignedToT = Joe.Bloggs or WHERE users.userName = Joe.Bloggs

 

There will be cases where Joe.Bloggs is assignedToT for many enquiries, but there is only one Joe.Bloggs in the user table.

 

Ok, so maybe you'd like something like:

SELECT enquiries.*, users.userName
FROM enquiries
LEFT JOIN users ON enquiries.assignedToT = users.userName
WHERE enquiries.enqState = 'New'
AND users.branch = '$userBranch'
ORDER BY enquiries.id DESC

 

Note that the join here isn't necessary because you can always get the userName from the enquiries table, as it's the same as assignedToT.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.