3

I have a table like this:

id     price    condition     username
----------------------------------------
 1       20     New           Kim 
 2       30     Used          Kim
 3       40     Used          George
 4       60     New           Tom

My question is about subselection. when I use this query,

SELECT *
FROM `table`
WHERE `username` = 'kim'
  AND `price` = '20'
   OR `condition` = 'New' 

it becomes true for the last condition and brings 2 records where condition = 'New'

However, when I use AND, it returns the correct record.

SELECT *
FROM `table`
WHERE `username` = 'kim'
  AND `price` = '20'
  AND `condition` = 'New'

I want to nest the query such that I can select price and condition only from the results of the first query, which is username. Thanks

2 Answers 2

3
SELECT * FROM table WHERE username = 'kim' AND (price = '20' OR condition = 'New');
Sign up to request clarification or add additional context in comments.

Comments

2

As Rafal Wojcik said you need to utilize some parenthesis to tell the database what OR you're grouping.

Without any guidence the engine groups all your conditionals as they come:

username = 'kim' AND price = 20 OR condition = 'New' 

reads as

((username = 'kim' AND price = 20) OR condition = 'New')

As you see this is not what you wanted. Here OR applies to "kim-20" OR "New"

Same issue is observed with your all AND case.

Good luck!

Comments

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.