I have a database table named order_data
that contains data like this:
id | order_id | data_value | data_key |
---|---|---|---|
9825 | 1156 | 2023-05-15 | date |
9826 | 1156 | 123 | product_id |
Each order (order_id
) generates these rows, so there can be multiple rows in this table which have the same order_id
.
How do I write a MySQL query to get the order_id
when:
data_key
=date
ANDdata_value
=2023-05-15
data_key
=product_id
ANDdata_value
=123
I know how to do this for each individual one above, but not sure if trying to account for both of the above together, can it be done in a single query?
I have tried:
SELECT order_id FROM `order_data` WHERE `data_key` = 'product_id' AND `data_value` = '123' AND `data_key` = 'date' AND `data_value` = '2023-05-15';
But this does not return the order_id
, returns no results.
2
Answers
One option would be using EXISTS
Consider the following data example
Query
An index on (order_id,data_value,data_key) will speed up the query
Demo
You can do it using
inner join
as follows :DISTINCT
will prevent getting duplicatesorder_id
if somehow one of the rows is duplicatedDemo here