0

有没有一种方法可以让我编写这个查询,以便将我的子查询的结果与我的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"

我希望电子计数取决于类别。即,第一行应该是 where category_id = 173,第二行应该是 where category_id = 42,第三行应该是 wherecategory_id = 211等等。

4

1 回答 1

4

要使您的相关子查询与同一个表一起工作,您必须使用表别名

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我转换FALSENULL. 因此只有那些行计数,其中product_path LIKE '%Electronics%'计算为TRUE

于 2013-11-15T05:28:58.417 回答