我有一个具有以下基本结构的数据库。
create table objects
(
id int auto_increment primary key,
);
create table object_attribute_values
(
id int auto_increment primary key,
object_id int not null,
attribute_id int not null,
value varchar(255) null
);
create table attributes
(
id int auto_increment primary key,
attribute varchar(20) null,
);
假设属性表有 3 个:
我需要选择所有颜色为“黑色”、评级为 IN (5, 10)、大小为 10 的对象。
我知道如何让所有的对象变成黑色
SELECT o.id
FROM objects o
INNER JOIN object_attribute_values oav ON oav.object_id = o.id
INNER JOIN join attributes a ON a.id = oav.attribute_id
WHERE a.attribute = 'color' AND oav.value = 'black'
结果应该是这样的:
最佳答案
您正在处理的是键/值表。我不太喜欢它们,因为它们使查询数据变得更加复杂,并且不能像普通列那样保证一致性(数据类型、强制/可选值)。但有时它们是必要的。
无论如何,查询键/值表的典型方式是通过聚合:
SELECT
o.id as object_id,
GROUP_CONCAT(CONCAT(a.attribute, ':', oav.value) ORDER BY a.id SEPARATOR ';') AS attributes
FROM objects o
INNER JOIN object_attribute_values oav ON oav.object_id = o.id
INNER JOIN join attributes a ON a.id = oav.attribute_id
GROUP BY o.id
HAVING SUM(a.attribute = 'color' AND oav.value = 'black') > 0;
HAVING
子句查找所有 color = black 的对象。其他人被解雇。这是可行的,因为在 MySQL 中 true = 1,false = 0,所以我们可以将条件结果相加。
关于MySQL。如何通过多列进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66063120/