problem
Query the data table (ball), which satisfy the color is orange, and the shape of the ball is round?
data sheet
solution
Option One
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'
Option two (similar to option one)
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'
The conventional table design is to use color
sum shape
as a field, but if you want to expand, you need to reserve some other fields. Then the query is simply that each field in multiple fields satisfies a value at the same time.
In the design of the table, the attributes and attribute values of a ball are extensible. Items that satisfy multiple attribute values will appear multiple times. So the general solution is the above solutions one and two, but consider a question, if the attribute value of a ball is inserted more and more, how long will our SQL be?
Solution Three (Optimal Solution)
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