Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP mysql subqueries filtering

Tags:

php

mysql

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

like image 945
karto Avatar asked Aug 25 '26 00:08

karto


2 Answers

SELECT * FROM table WHERE username = 'kim' AND (price = '20' OR condition = 'New');
like image 190
Rafał Wójcik Avatar answered Aug 27 '26 13:08

Rafał Wójcik


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!

like image 26
Mikhail Avatar answered Aug 27 '26 14:08

Mikhail



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!