0

i need some help with select statement.

table: mobiles (brand,model,price)

i tried the below syntax to fetch the content.

select * 
from mobiles 
where brand in ('apple','nokia','samsung') 
      and model in ('lumia 510','galaxy s3')

the above query is showing only "nokia lumia 510" and "samsung galaxy s3".

i want it to display all models in 'apple', only 'lumia 510' from 'nokia' and 'galaxy s3' from 'samsung'.

am i wrong at using the syntax?

i am developing a site where users can filter mobiles by brand and model. i need to display only the mobiles what user's select. for each brand if the user select's specific model, then, only that model should be displayed, if he selects only the brand then all the mobiles under that brand should be displayed.

he can choose any number of brands, and under each brand he might or might not select the specific model.

2
  • 1
    Try use "OR" instead of "AND" in your query Commented Feb 22, 2013 at 23:20
  • i tried it. but its displaying all the models in nokia and samsung. Commented Feb 22, 2013 at 23:32

1 Answer 1

1

You can't do this with IN, because each brand has different model requirements.

SELECT *
FROM mobiles
WHERE (brand = 'apple')
OR (brand = 'nokia' AND model = 'nokia lumia 510')
OR (brand = 'samsung' AND model = 'galaxy s3')

If models are always unique to a specific brand, you can simplify it a bit:

SELECT *
FROM mobiles
WHERE brand IN ('apple')
OR model IN ('nokia lumia 510', 'galaxy s3')

Put all the brands that have no model selected in the first IN clause, and all the models in the second one. The brand is implied by the model, because of the unique relationship.

Sign up to request clarification or add additional context in comments.

3 Comments

wowww. thats an awesome solution. thanks for the quick reply.
i need to add one more condition to it. "and condition=used". its not working.
Make sure you parenthesize properly. AND binds more tightly than OR. brand in X OR model in Y AND condition = Z is equivalent to brand in X OR (model in Y AND condition = Z).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.