I have a table named items
as follows:
id oId key value
1 0 color green
2 0 size 30
3 1 color red
4 2 color blue
Above rows with oId=0
specifies the default values of items .
I need to select all key
, value
of an item with a particular oId
which will include the default (oId=0), if a specific key
and value
for that oId
does not exists.
For eg. For item 2 , it should return
id oId key value
1 0 size 30
2 2 color blue
I have written the following query:
SELECT * FROM items AS i
WHERE i.oId=0 AND
i.key NOT IN (SELECT key FROM items WHERE oId=2)
UNION ALL
SELECT * FROM items WHERE oId=2
Is there a way to optimize the above query ?
You can use the OR condition in the WHERE clause to test multiple conditions where the record is returned if any one of the conditions are met. This example uses the WHERE clause to define multiple conditions, but instead of using the AND condition, it uses the OR condition.
As can be seen from the documentation of DELETE, it can take two FROM clauses. The first FROM : FROM: Is an optional keyword that can be used between the DELETE keyword and the target table_or_view_name, or rowset_function_limited.
IF statements can be used to conditionally enter into some logic based on the status of a condition being satisfied. The IF statement is logically equivalent to a CASE statements with a searched-case-statement-when clause.
You can use JOIN on the right index:
SELECT t1.`key`, IFNULL(t2.value, t1.value)
FROM `items` AS t1
LEFT JOIN `items` AS t2
ON t1.`key` = t2.`key` AND t2.`oId` = 2
WHERE t1.`oId` = 0;
SQLFiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With