Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL:特定类别的独特产品计数_Mysql_Sql - Fatal编程技术网

MySQL:特定类别的独特产品计数

MySQL:特定类别的独特产品计数,mysql,sql,Mysql,Sql,我有三张桌子: 产品 类别 类别产品(用于“多对多”关系) “类别产品”表示例: +-------------+------------+ | category_id | product_id | +-------------+------------+ | 3 | 9 | | 3 | 28 | | 3 | 100 | | ... | ... | |

我有三张桌子:

  • 产品
  • 类别
  • 类别产品
    (用于“多对多”关系)
“类别产品”表示例:

+-------------+------------+
| category_id | product_id |
+-------------+------------+
|           3 |          9 |
|           3 |         28 |
|           3 |        100 |
|         ... |        ... |
|           7 |         13 |
|           7 |         21 |
|           7 |         81 |
|           7 |        100 |
|         ... |        ... |
|          25 |         22 |
|          25 |         28 |
|          25 |        100 |
+-------------+------------+

我需要找到这个类别中独特产品的数量。在我的例子中,我必须从
COUNT
行中排除,其中
product\u id=28
和100。如何做到这一点?

我认为这应该是可行的:

SELECT
    c.*,
    COALESCE( cnts.distinct_product_count, 0 ) AS distinct_product_count
FROM
    categories AS c
    LEFT OUTER JOIN
    (
        SELECT
            category_id,
            COUNT( DISTINCT product_id ) AS distinct_product_count
        FROM
            category_product
        WHERE
            product_id NOT IN ( 28, 100 )
        GROUP BY
            category_id

    ) AS cnts ON
        cnts.category_id = c.category_id

使用一个不同的计数

架构(MySQL v5.7)


查询#1

SELECT COUNT(DISTINCT product_id)  FROM category_product
WHERE `category_id` IN (3,7,25);

| COUNT(DISTINCT product_id) |
| -------------------------- |
| 7                          |


您可以使用
不存在
排除属于一个以上类别的产品:

SELECT cp.category_id, COUNT(*) counter
FROM category_product cp
WHERE NOT EXISTS (SELECT 1 FROM category_product WHERE product_id = cp.product_id AND category_id <> cp.category_id)
GROUP BY cp.category_id
作为在中使用运算符
的子查询:

SELECT category_id, COUNT(*) counter
FROM category_product
WHERE product_id IN (
  SELECT product_id
  FROM category_product
  GROUP BY product_id
  HAVING COUNT(*) = 1
)
GROUP BY category_id
请参阅。
结果:


为什么一个类别会有非唯一的产品?
category\u product
是否定义了复合键?因为存在这样一个条件:一个产品可以属于不同的类别。复合密钥已定义。谢谢!这就是我需要的!
SELECT product_id
FROM category_product
GROUP BY product_id
HAVING COUNT(*) = 1
SELECT category_id, COUNT(*) counter
FROM category_product
WHERE product_id IN (
  SELECT product_id
  FROM category_product
  GROUP BY product_id
  HAVING COUNT(*) = 1
)
GROUP BY category_id
category_id | counter
----------: | ------:
          3 |       1
          7 |       3
         25 |       1