我正在尝试运行此查询:
SELECT
gc_category_products.product_id,
LEAST(IFNULL(NULLIF(saleprice, 0), price),price) AS sort_price,
GROUP_CONCAT(CONVERT(category_id, CHAR(8))) AS cats
FROM
(`gc_category_products`)
JOIN `gc_products` ON `gc_category_products`.`product_id` = `gc_products`.`id`
WHERE
`category_id` = '31'
OR `category_id` = '35'
OR `category_id` = '30'
OR `category_id` = '36'
OR `category_id` = '37'
OR `category_id` = '34'
AND
`enabled` = 1
GROUP BY
`product_id`
LIMIT 10
在cats
字段中,它只返回一个数字,如果我取出所有WHERE子句,它会带回一个以逗号分隔的列表,但我需要那些WHERE来过滤我的数据。
有什么想法吗?
示例数据
gc_category_products
--------------------------
product_id | category_id |
--------------------------
3 | 31 |
3 | 18 |
4 | 35 |
4 | 21 |
gc_products
-----------------------------------
| id | price | saleprice | enabled|
-----------------------------------
| 3 | 23.00 | 0.00 | 1 |
| 4 | 50.00 | 0.00 | 1 |
expected result
--------------------------------
product_id | sort_price | cats |
--------------------------------
| 3 | 23.00 | 31,18|
| 4 | 50.00 | 35,21|
答案 0 :(得分:5)
对我而言,这听起来像你想要的,你想要某些类别的产品,包括他们所在的所有类别的列表; < / p>
SELECT
cat.product_id,
LEAST(IFNULL(NULLIF(saleprice, 0), price),price) AS sort_price,
GROUP_CONCAT(category_id) AS cats
FROM gc_category_products cat
JOIN gc_products p ON cat.product_id = p.id
WHERE cat.product_id IN
(SELECT product_id
FROM gc_category_products gcp
WHERE gcp.category_id IN ('31','35','30','36','37','34'))
AND enabled=1
GROUP BY product_id
PRODUCT_ID SORT_PRICE CATS
3 23 31,18
4 50 35,21
答案 1 :(得分:3)
WHERE
子句会过滤掉您在结果集中预期的其他category_id
:'18'
和'21'
。此查询生成所需的结果集:
SELECT
gc_category_products.product_id,
LEAST(IFNULL(NULLIF(saleprice, 0), price),price) AS sort_price,
GROUP_CONCAT(CONVERT(category_id, CHAR(8))) AS cats
FROM
(`gc_category_products`)
JOIN `gc_products` ON `gc_category_products`.`product_id` = `gc_products`.`id`
WHERE
`category_id` = '31'
OR `category_id` = '35'
OR `category_id` = '30'
OR `category_id` = '36'
OR `category_id` = '37'
OR `category_id` = '34'
OR `category_id` = '18' /* added */
OR `category_id` = '21' /* added */
AND
`enabled` = 1
GROUP BY
`product_id`
LIMIT 10
可以在此处找到生成预期结果集的测试示例:http://sqlfiddle.com/#!2/71a20/17
但,请注意您的查询还有其他潜在问题。
OR
logical operator has lower precedence than AND
。因此,您的查询可能无法达到预期效果。 如果Joachim has correctly interpreted your intent,您应该修改WHERE
子句以包含执行过滤的子查询。以这种方式构建查询可确保不从最终结果集中过滤其他类别。
WHERE
enabled
= 1
和EXISTS(
选择1
从gc_category_products
起x
在x
。product_id
= gc_products
。id
和x
。category_id
IN
( '31', '35', '30', '36', '37', '34')
)
此附加修改已经过测试,符合您的规范:http://sqlfiddle.com/#!2/71a20/21/0