1

我正在尝试运行此查询:

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|
4

2 回答 2

5

对我来说,这听起来像是您想要的,您想要某些类别的产品,包括它们所在的所有类别的列表;

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

用于测试的 SQLfiddle

于 2013-01-24T19:13:14.710 回答
3

WHERE子句过滤掉category_id您在结果集中期望的额外 s:'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


但是,请注意您的查询还有其他潜在问题。

  1. 逻辑运算符的OR优先级低于AND。因此,您的查询可能不会达到您的预期。
  2. 如果 Joachim正确解释了您的意图,您应该修改您的WHERE子句以包含执行过滤的子查询。以这种方式构建查询可确保不会从最终结果集中过滤掉其他类别。

    WHERE enabled= 1 AND EXISTS ( SELECT 1 FROM gc_category_productsas x WHERE x. product_id= gc_products. id AND x. category_idIN ('31','35','30','36','37','34') )

此处测试此附加修改是否符合您的规范:http: //sqlfiddle.com/# !2/71a20/21/0

于 2013-01-24T18:40:07.873 回答