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



有没有办法编写这个查询,以获得与我的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的地方,等等。

若要使相关子查询与同一表一起使用,必须使用表别名

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 .

相关内容

  • 没有找到相关文章

最新更新