I am building a query to gather data from multiple tables. I want to grab all of the item_ids from one table and then build the results by gathering other data from other tables based on that item_id. I could have sworn that this was possible; but, I can’t seem to get it to work. Here is an example of what I’m trying to do:
SELECT item_id AS mainID,
(SELECT anotherField
FROM anotherTABLE
WHERE item_id=mainID)
FROM theMainTable;
Granted that is just an example. Essentially, I need to use the item_id from the main query inside the subquery. I could have sworn that I’d done this before, but I can’t remember how…
I’m trying to do this with just a query, not with any extra programming languages. I’d like to eventually set it as a stored procedure. Thanks or any assistance with this.
UPDATE
Looks like a join did work… Thanks for all the assistance.
Here is my final query just in case anyone else runs into something like this:
SELECT DISTINCT
Q.item_id, Q.timestamp, Q.employee,
QA.employeeNotes, Q2.itemDesc, Q2.itemExtraData
FROM
itemLog Q
LEFT JOIN
itemComments QA ON Q.item_id = QA.item_id
LEFT JOIN
itemLog Q2 ON Q.item_id = Q2.item_id AND Q2.type = 'begin'
WHERE
Q.verb = 'itemStatus'
AND NOT (QA.employeeNotes IS NULL);
You should avoid using subqueries in select statements, because they will be computed for each returned row from the main table, whereas the inner join ensures proper optimization and tables paths.