how to select count from main query into subquery

2019-03-07 09:42发布

I want to get the number of records that are selected in the main query into a subquery

Query that i am currently trying to execute is:

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条回答
淡お忘
2楼-- · 2019-03-07 10:39

You cannot put the HAVING clause on the outer query because it is not an aggregate query. Try this instead:

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;
查看更多
我只想做你的唯一
3楼-- · 2019-03-07 10:40

You can just use a join between the two tables instead of the correlated subquery:

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; 

Edit, based on your update, you should still be able to use something like this:

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;

Or even use:

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;
查看更多
登录 后发表回答