我有这样的表:
id | meta_key | meta_value
-------------
1 | color | red
1 | price | 10
2 | color | red
2 | price | 20
3 | color | blue
3 | price | 10
如何获得所有唯一 ID 为 color=red 和 price=10 。我可以通过单个简单查询获得它吗?没有枢轴等。
最佳答案
我喜欢使用 group by
和 having
来处理这些问题:
select id
from t
where (meta_key = 'color' and meta_value = 'red') or
(meta_key = 'price' and meta_value = '10')
group by id
having count(distinct meta_key) = 2;
另一种方法是join
。如果 id
没有重复值:
select id
from t tc join
t tp
on tc.id = tp.id and
tc.meta_key = 'color' and tc.meta_value = 'red' and
tp.meta_key = 'price' and tp.meta_value = '10';
group by
方法具有可扩展性和可表达性的优点。很容易表达许多不是简单相等的条件(颜色不是红色,在美国或中国制造)。此外,附加条件具有非常相似的性能。
第二个可能在一些条件下表现更好(使用正确的索引)。
关于php - 构建 MySQL 查询(meta_key/meta_value 表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36101969/