tags:

views:

56

answers:

4

Say I have a table that has id and brand columns.

Say I have an item I know the ID is 300, but that's all I know. Is there a way to make a query pull all the items with the same brand as the item, or do I have to break it into 2 queries and first select the brand of item 300?

Thanks.

A: 
select id
from item
where brand = (select brand from item where id = 300)
sheepsimulator
+3  A: 

If I understood you correctly, using a subselect might be the easiest way to solve that problem.

SELECT * FROM mytable WHERE brand = (SELECT brand FROM mytable WHERE id = 300 );
hangy
I think I will use your answer, although I think Eric's answer is cooler I think your's would be easier for me to look back at later and understand what it is doing.
John Isaacks
+3  A: 

You can join the table to itself:

select
    a.*
from
    brands a
    inner join brands b on
        a.brand = b.brand
where
    b.id = 300
Eric
Yours as hangy's both work, I wonder which one out performs...I would think your way because there is no sub-query?
John Isaacks
@John: In this case, the optimizer will make them exactly the same. If you use a subquery which is dependent on the superquery (e.g.-where brand = (select b.brand from mytable2 b where b.id = a.id)), then the join would _generally_ be faster. I just prefer joins in this case because they're easier for me to read.
Eric
A: 
select * from products where category in (select category from products where Id = 300)
Hardwareguy