I am working on an inventory php/mysql application.
I have a main table (inv_main) which will hold the equipmentID and the userID whom actually holds this equipment.
I then have a equiptment table (inv_equip) which holds information about the piece of equipment as well as who ordered the product, and who it was ordered for, both linking back to userIDs.
I am trying to return a result of the equipmentID, ownerName, orderedByName, orderedForName
When I run the following query I get NULLs for orderedByName, and OrderedForName which should both return names as those fields have IDs and are not null.
SELECT inv_equip.tech_id, inv_user.user_lname as ownedByName,
orderFor.user_lname as orderForName, orderFrom.user_lname as orderFromName
FROM inv_main
LEFT JOIN inv_equip ON inv_main.main_equip_id = inv_equip.equip_id
LEFT JOIN inv_user ON inv_main.main_user_id = inv_user.user_id
LEFT JOIN inv_user as orderFor ON inv_equip.equip_ordered_for = inv_user.user_id
LEFT JOIN inv_user as orderFrom ON inv_equip.equip_ordered_from = inv_user.user_id
WHERE (inv_main.main_equip_id = 26)
This is what I am getting for my output
tech_id ownedByName orderForName orderFromName
TCH20110305_1299355914 admin NULL NULL
Now if i run this query I am getting the correct ownedByname again but the orderForName return i record for each user in my user table. The difference is I am not specifying to return a certain id but all in the db.
SELECT inv_equip.tech_id, inv_user.user_lname AS ownedByName,
orderFor.user_lname AS orderForName, orderFrom.user_lname AS orderFromName
FROM inv_main
LEFT JOIN inv_equip ON inv_main.main_equip_id = inv_equip.equip_id
LEFT JOIN inv_user ON inv_main.main_user_id = inv_user.user_id
LEFT JOIN inv_user AS orderFor ON inv_equip.equip_ordered_for = inv_user.user_id
LEFT JOIN inv_user AS orderFrom ON inv_equip.equip_ordered_from = inv_user.user_id
I am getting the following results
OwnedBy OrderedFor OrderedBy
TCH20110304_1299257155 hucker admin NULL
TCH20110304_1299257155 hucker hucker NULL
TCH20110304_1299257155 hucker beatty NULL
TCH20110304_1299257155 hucker Frank2 NULL
TCH20110304_1299257245 beatty admin admin
TCH20110304_1299257245 beatty admin hucker
TCH20110304_1299257245 beatty admin beatty
Where as I am looking for a sql query which results in
itemID OwnedBy OrderedFor OrderedBy
x Hucker Beatty Frank
Any tips on how I could correct my join logic to return the names of the respected userID with only one record?
Your 2nd and 3rd joins specify an
oncondition against the 1st join:Try modifying the code so each join uses it’s own table:
The
**are just there for emphasis.