将子查询添加到依赖于第一列的SELECT语句?

时间:2013-11-15 04:48:45

标签: mysql sql postgresql aggregate-functions correlated-subquery

我是否可以通过某种方式编写此查询,以获取与我的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等等。

1 个答案:

答案 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 NULLcount(*)。然后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}}。