Let’s say I have a Item and Person table, where the Person ‘id’ column matches the Item ‘person_id’ column. I want to retrieve records in the Item table where the owner (Person) of the Item has ‘category’ 1. Sample structure below:
Item |
---|
id |
item_name |
person_id |
Person |
---|
id |
name |
category (can be 1, 2, or 3) |
I understand that I can use ‘join’ to find rows of the Item table where the two ids match, but I cannot use join for my use case. I need my SQL query to return only Item columns, and not Person columns. Basically, how can I construct a query that will query a table using values in another table, while still maintaining the original table structure?
Advertisement
Answer
I understand that I can use ‘join’ to find rows of the Item table where the two ids match, but I cannot use join for my use case. I need my SQL query to return only Item columns, and not Person columns.
This statement is just false. You can select whatever columns you want when joining:
select i.* from items i join persons p on i.person_id = p.id and p.category = 1;
In terms of constructing the query, exists
is also a very reasonable approach, but you can definitely use join
.