返回产品ID及其计数,即使mysql中没有相应的变量
我有三张桌子:返回产品ID及其计数,即使mysql中没有相应的变量,mysql,Mysql,我有三张桌子: table_products - product_id, pname variants - vid, vname table_product_varients - product_id, vid 我想获得所有产品的产品变体计数,如果没有产品变体,则计数应为0 这是我的疑问: SELECT P.product_id, count(*) AS count FROM table_product_varients AS PV LEFT JOIN table_products AS P
table_products - product_id, pname
variants - vid, vname
table_product_varients - product_id, vid
我想获得所有产品的产品变体计数,如果没有产品变体,则计数应为0
这是我的疑问:
SELECT P.product_id, count(*) AS count
FROM table_product_varients AS PV
LEFT JOIN table_products AS P ON PV.product_id = P.product_id
GROUP BY P.product_id
ORDER BY P.product_id ASC
但这并不是提供没有变体的产品
有人能帮我吗?你应该把
表(产品
表)放在左侧
。
此外,您还应该计算PV.product\u id
SELECT
P.product_id,
count(PV.product_id) AS count
FROM table_products AS P
LEFT JOIN table_product_varients AS PV ON PV.product_id = P.product_id
GROUP BY P.product_id
ORDER BY P.product_id ASC;
注意:对于那些在表\u products\u variants
表中没有相应条目的产品,您将获得NULL
值PV.product\u id
。因此COUNT(NULL)
实际上返回0
关于计数的一些微妙之处
:
SELECT COUNT(0); Result: 1
SELECT COUNT(-1); Result: 1
SELECT COUNT(NULL); Result: 0
SELECT COUNT(71); Result: 1
我尝试了这个查询。但是它仍然没有返回任何没有变化的行。在这之后,我做了一个小的更改。你能再试一次吗?如果您得到的结果与预期不同,请共享一个sql fiddle.same结果。1-1,2-1,3-1,4-7,7-1…基本上我需要1-1,2-1,3-1,4-7,5-0,6-0,7-1。你能分享一个sql数据吗?你能告诉我哪个表包含所有的产品吗?是不是
表_产品
?