I have the following table (simplified non-sense example):
table fruits:
+-----+---------+-------------+
| id | fruit | customer_id |
+-----+---------+-------------+
| 1 | apple | 1 |
| 2 | pear | 2 |
| 3 | kiwi | null |
| 4 | mango | 1 |
| 5 | guava | 2 |
| 6 | kiwi | 1 |
| 7 | kiwi | 2 |
| 8 | khaki | null |
| 9 | date | null |
| 10 | date | 1 |
+-----+---------+-------------+
Fruits can be assigned to a customer (customer_id). If they are not assigned to a customer (customer_id IS NULL), they are relevant for every customer.
Fruits can occur multiple times with the same name (but for a customer only once), i.e. such a thing does not occur in the table:
+---------+------------+
| fruit | customer_id |
+-----+---------+------+
| apple | 1 |
| apple | 1 |
+-----+---------+------+
I use the following query to get all the fruits where the customer_id is null or the customer_id matches a certain value (in this example customer_id = 1). For fruits that occur twice (in this case kiwi and date), I want to get the rows where the customer_id is not null.
SELECT * FROM fruits WHERE customer_id = 1 OR (customer_id IS NULL AND fruit NOT IN (SELECT fruit FROM fruits WHERE customer_id = 1))
Result:
+-----+---------+-------------+
| id | fruit | customer_id |
+-----+---------+-------------+
| 1 | apple | 1 |
| 4 | mango | 1 |
| 6 | kiwi | 1 |
| 8 | khaki | null |
| 10 | date | 1 |
+-----+---------+-------------+
Is there a better query (better performing)? Thank you very much!