I've got three tables in a mySQL DB:
tbl_user
and tbl_item
and tbljn_userItem
(a table containing the primary keys to the first two, in a many-to-many relationship.)
I want to create a SQL statement that will return a list of all the items from tbl_item
with a flag value that identifies those items that are assigned to a specific userID (tbl_user
primary key).
Essentially a combination/derivative of:
SELECT tbl_item.*
FROM tbl_item, tbljn_userItem
WHERE tbljn_useritem.userID=tbl_user.userID
and
SELECT * FROM tbl_item
SQL is not my first language so if this is an obvious Q, my apologies.
tbl_user
|- userID -|- firstName -|- lastName -|- streetAddress -|- city -|
tbl_item
|- itemID -|- name -|- description -|- category -|- cost -|
tbljn_userItem
|- userID -|- itemID -|
So, I'd give the SQL statement the userID and it would hopefully return (example):
|- itemID -|- name -|- description -|- category -|- cost -|- isOwned -|
|- itemID -|- name -|- description -|- category -|- cost -|- isOwned -|
|- itemID -|- name -|- description -|- category -|- cost -|- isOwned -|
|- itemID -|- name -|- description -|- category -|- cost -|- isOwned -|
Where isOwned
is a boolean indicating that this item's itemID
was listed in tbljn_userItem
in the same record as the passed userID
.
I realize I could easily do this in my source code, not SQL. However, I'd like to do this "the right way" and have it optimized. Am I mistaken in my assumption that if I do this on the SQL side, it will be more efficient? I'm doing multiple users at runtime and I felt it would be more efficient to do one DB call per.
All help is appreciated!