gpt4 book ai didi

mysql - 有没有更好的方法来获取具有所需属性和有效值的所有产品?

转载 作者:行者123 更新时间:2023-11-29 15:43:32 25 4
gpt4 key购买 nike

我想从以下表结构中获取包含一组必需属性的所有产品:

product

uid | name
---------------
1 | Product A
2 | Product B
3 | Product C


attribute_set

uid | product | attribute | attribute_value
-------------------------------------------
1 | 1 | 2 | 4
2 | 1 | 2 | 5
3 | 1 | 3 | 10
4 | 2 | 2 | 4
5 | 2 | 3 | 10

例如,我想获取拥有值为 4 和 5 的属性 2 以及拥有值为 10 的属性 3 的所有产品。

为了实现此目的,我当前正在使用如下查询:

SELECT product.uid,
(
SELECT COUNT(*)
FROM attribute_set
WHERE attribute_set.attribute = 2
AND attribute_set.attribute_value IN (4,5)
AND product.uid = attribute_set.product
) as counter,
(
SELECT COUNT(*)
FROM attribute_set
WHERE attribute_set.attribute = 3
AND attribute_set.attribute_value IN (10)
AND product.uid = attribute_set.product
) as counter2
FROM product
LEFT JOIN attribute_set
ON product.uid = attribute_set.product
GROUP BY product.uid
HAVING counter = 2 AND counter2 = 1

所以我必须检查每个属性所需值的数量是否与子查询计数器值匹配。这对我有用,但是有没有办法做得更好?

最佳答案

试试这个,我通过删除子查询使用了 joincase

SELECT p.uid,
COUNT(CASE WHEN a.attribute = 2 AND a.attribute_value IN (4,5) THEN 1 END) AS counter1,
COUNT(CASE WHEN a.attribute = 3 AND a.attribute_value IN (10) THEN 1 END) AS counter2
FROM product p
JOIN attribute_set a ON p.uid = a.product
GROUP BY p.uid
HAVING counter1 = 2 AND counter2 = 1

关于mysql - 有没有更好的方法来获取具有所需属性和有效值的所有产品?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57322241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com