问题
查询出数据表(ball)中,满足颜色是橙色,并且形状是圆形的球有哪些?
数据表
解决方案
方案一
SELECT
name
FROM
ball
WHERE
NAME IN (
SELECT
NAME
FROM
ball
WHERE
attribute = 'color'
AND attribute_value = 'orange'
)
AND attribute = 'shape'
AND attribute_value = 'circle'
方案二(与方案一类似)
SELECT
a. NAME
FROM
ball AS a
JOIN ball AS b ON a. NAME = b. NAME
WHERE
a.attribute = 'color'
AND a.attribute_value = 'orange'
AND b.attribute = 'shape'
AND b.attribute_value = 'circle'
常规的表设计是将color
和shape
作为字段,但是如果要扩展就需要预留一些其他字段。那么查询就简单的是多个字段中每个字段,同时满足一个值。
该表的设计中,一个球的属性与属性值是可扩展的。满足多个属性值的物品会出现多次。所以一般的解决方案就是上面的方案一与方案二,但是考虑一个问题,如果一个球的插入的属性值越来越多的时候,我们的sql会有多长?
方案三
SELECT
NAME
FROM
(
SELECT
NAME,
count(NAME) AS count
FROM
ball
WHERE
(attribute, attribute_value) IN ( //这里很秀!
('color', 'orange'),
('shape', 'circle')
)
GROUP BY
NAME
) AS stat
WHERE
stat.count = 2