如何从主查询到子查询中选择计数

时间:2013-01-16 11:30:21

标签: mysql subquery

我想将主查询中选择的记录数量提取到子查询中

我当前正在尝试执行的查询是:

SELECT cat_id,category_name,seo_name,(SELECT count(category_name) FROM ccs_coupons WHERE (category_name LIKE category_name OR website_name LIKE category_name OR description LIKE LIKE category_name OR url_desc LIKE category_name )) FROM  `ccs_coupons` WHERE  category_name like 'a%' GROUP BY category_name ORDER BY category_name ASC LIMIT $page,$config 

2 个答案:

答案 0 :(得分:0)

您可以使用两个表之间的连接而不是相关子查询:

SELECT c.id,
  u.display_name, 
  c.comments_count 
FROM users u
LEFT JOIN
(
  SELECT COUNT(*) comments_count, author_id
  FROM cms_comments 
  GROUP BY author_id
) c
   ON c.author_id = u.id
WHERE c.comments_count > 150; 

编辑,根据您的更新,您仍然可以使用以下内容:

SELECT c1.cat_id,
  c1.category_name,
  c1.seo_name,
  c2.CountCategoryName
FROM  `ccs_coupons` c1
LEFT JOIN
(
  SELECT count(category_name) CountCategoryName, category_name,
       website_name, description, url_desc
   FROM ccs_coupons 
  GROUP BY category_name
) c2
  on c2.category_name LIKE c1.category_name 
  or c2.website_name LIKE c1.category_name 
  or c2.description LIKE c1.category_name 
  or c2.url_desc LIKE c1.category_name
WHERE  c1.category_name like 'a%' 
ORDER BY c1.category_name ASC 
LIMIT $page,$config;

甚至使用:

SELECT c1.cat_id,
  c1.category_name,
  c1.seo_name,
  count(c2.category_name)
FROM  `ccs_coupons` c1
INNER JOIN ccs_coupons c2
  on c2.category_name LIKE c1.category_name 
  or c2.website_name LIKE c1.category_name 
  or c2.description LIKE c1.category_name 
  or c2.url_desc LIKE c1.category_name
WHERE  c1.category_name like 'a%' 
GROUP BY c1.category_name
ORDER BY c1.category_name ASC 
LIMIT $page,$config;

答案 1 :(得分:0)

您不能将HAVING子句放在外部查询上,因为它不是聚合查询。试试这个:

SELECT users.id,
       users.display_name, 
       COUNT(*) AS comments_count 
  FROM users 
  INNER JOIN cms_comments 
  ON users.id = cms_comments.author_id
GROUP BY users.id, users.display_name
HAVING COUNT(*) > 150;