假设我们的数据库中有衬衫。所有的衬衫都有尺寸和颜色(以及许多其他选项,但是现在我想用两个来解决这个问题。)
表格如下:
+-------------------------+--------------+--------------+-----------+
| variation_attributes_id | variation_id | attribute_id | option_id |
+-------------------------+--------------+--------------+-----------+
| 1 | 1 | size | s |
| 2 | 1 | color | red |
| 3 | 2 | size | m |
| 4 | 2 | color | red |
| 5 | 3 | size | s |
| 6 | 3 | color | green |
| 7 | 4 | size | m |
| 8 | 4 | color | green |
+-------------------------+--------------+--------------+-----------+
如何选择唯一variation_id
。例如,size
为S
且color
为Green
时应返回variation_id
== 3.
答案 0 :(得分:2)
你可以用一个简单的mul.s $f4,$f3,$f0
(自连接,这意味着你在特定条件下自己加入表)。假设您的表名为JOIN
,它就像这样:
shirts
它将返回所有具有您需要的颜色和大小的variation_id,过滤掉所有其他的variation_id。
此查询可以正常运行,如果您拥有和SELECT DISTINCT s1.variation_id
FROM shirts s1
JOIN shirts s2 ON s1.variation_id = s2.variation_id
WHERE (s1.attribute_id = 'size' AND s1.option_id='s')
AND (s2.attribute_id = 'color' AND s2.option_id='green')
此外,此查询可让您使用更复杂的参数获取(variation_id, attribute_id, option_id)
,使用variation_ids
会更加困难。
例如 - 您需要找到尺寸为'的所有HAVING COUNT(*) = ?
。或者' m'和'绿色'的颜色或者'黄色'
variation_ids
答案 1 :(得分:0)
您可以在where
子句中提供必要条件,并在count
子句中having
出现{<1}}:
select variation_id
from tbl
where ( attribute_id = 'size' and option_id = 's' )
or ( attribute_id = 'color' and option_id = 'green' )
group by variation_id
having count(*) = 2
答案 2 :(得分:0)
您可以使用EXISTS
和子查询:
SELECT variation_id
FROM your_table t1
WHERE attribute_id = 'color'
AND option_id = 'green'
AND EXISTS (SELECT 1
FROM your_table t2
WHERE t1.variation_id = t2.variation_id
AND t2.attribute_id = 'size'
AND t2.option_id = 's');
答案 3 :(得分:0)
SELECT T1.`variation_id`
FROM(
(SELECT *
FROM table_name
WHERE `attribute_id` = 'size') T1
INNER JOIN
(SELECT *
FROM table_name
WHERE `option_id ` = 's') T2 ON T1.`variation_id` = T2.`variation_id`)
希望这有帮助。