我是否可以通过某种方式编写此查询,以获取与我的category_id
相比较的子查询结果。
SELECT category_id,
count(id) as TOTAL COUNT,
(select count(*) from products where product_path LIKE '%Electronics%'
and category_id = category_id ) as ELECTRONIC COUNT
FROM products
WHERE product_path LIKE '%Products%'
GROUP BY category_id
我想以下面的方式结果:
"category_id" "TOTAL COUNT" "ELECTRONIC COUNT"
"173" "1" "243"
"42" "1" "243"
"211" "41" "243"
"162" "10" "243"
"172" "139" "243"
"116" "54" "243"
"10" "3" "243"
我希望电子计数取决于类别。即,第一行应该是category_id = 173
,第二行应该是category_id = 42
,第三行应该是category_id = 211
等等。
答案 0 :(得分:4)
要使相关子查询与同一个表一起使用,您必须使用table aliases:
SELECT category_id
,count(*) AS total_count -- unquoted column alias with space is wrong, too
,(SELECT count(*)
FROM products AS p1
WHERE product_path LIKE '%Electronics%'
AND p1.category_id = p.category_id
) AS electronic_count
FROM products AS p
WHERE product_path LIKE '%Products%'
GROUP BY category_id;
假设id
是主键,因此NOT NULL
。count(*)
。然后SELECT category_id
,count(*) AS total_count -- keyword AS is needed for column alias
,count(product_path LIKE '%Electronics%' OR NULL) AS electronic_count
FROM products p -- keyword AS is just noise for table alias
WHERE product_path LIKE '%Products%'
GROUP BY category_id;
做得更好。
但这可以进一步简化到:
count()
快得多。
OR NULL
仅计算非空值。添加FALSE
我将NULL
转换为product_path LIKE '%Electronics%'
。因此,只有那些行计数,TRUE
评估为{{1}}。