MySQL / MariaDB structure:
Person
| id |
|----|
| 1 |
| 2 |
| 3 |
Car
| person_id | car |
|-----------|-------|
| 1 | Ford |
| 2 | Mazda |
| 3 | Ford |
| 3 | Mazda |
| 3 | BMW |
What query can get the Persons with exactly 1 car, and car is not Mazda ?
expected output is person id 1.
Note:
if GROUP BY is used, query should be full group by, otherwise getting the following error, and changing the SQL configuration is not wanted.
"In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column ‘X’; this is incompatible with sql_mode=only_full_group_by"
2
Answers
You can use aggregation and
having
to filter:We can get the result directly from the
car
table. If for some reason you need to bring the corresponding row fromperson
, we canjoin
:Another option, use the negate of the
EXISTS
operator on a correlated subquery as follows:demo