Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

better way to condition preference sql

Tags:

sql

php

mysql

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 ?

like image 760
adi rohan Avatar asked Sep 26 '14 15:09

adi rohan


People also ask

How to use more than one WHERE condition in SQL?

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.

Can you use 2 from clauses in SQL?

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.

Can you use if in SQL?

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.


1 Answers

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

like image 127
Andrey Bakharev Avatar answered Sep 29 '22 02:09

Andrey Bakharev