mysql show Count of rows from other table in each row

大憨熊 提交于 2020-01-11 08:45:30

问题


select `personal`.`id` AS `id`,
`personal`.`name` AS `name`,
(select count(visit.id) 
      from visit,personal 
        where visit.user_id=personal.id) as count 
from personal;

im trying to get all users and the counts of visits they did.

the result i get is all users but the count column contain same value (not specific to that row id).

what am i doing wrong here ? how to tell mysql to user this row id ?

is compound select optimum way to do it or is there a better way ?


回答1:


SELECT  p.id, p.name, COUNT(v.user_id)
FROM    personal p
LEFT JOIN
        visit v
ON      v.user_id = p.id
GROUP BY
        p.id

You may also use subselect of course (for instance if you have ANSI GROUP BY compatibility on):

SELECT  p.id, p.name,
        (
        SELECT  COUNT(*)
        FROM    visit v
        WHERE   v.user_id = p.id
        )
FROM    personal p



回答2:


try this

 SELECT
Pe.id AS id,Pe.name AS name,COUNT(v.user_id) number_visit
FROM personal Pe
LEFT JOIN visit Vi
   ON Vi.user_id= Pe.id
GROUP BY Pe.id



回答3:


Try this:

select
   p.id AS `id`,
   p.name AS `name`, 
   IFNULL(v.TheCount, 0) TheCount
from personal p
LEFT JOIN
( 
  SELECT user_id, COUNT(*) TheCount
  FROM visits v
  GROUP BY user_id
) v ON v.user_id = p.Id;



回答4:


That will work with LEFT JOIN tables personal with visit.

SELECT 
    Pe.id AS id, Pe.name AS name, COUNT(v.user_id) number_visit
FROM
    personal Pe
LEFT JOIN
    visit Vi ON Vi.user_id = Pe.id
GROUP BY Pe.id

If you want only user which are having atleast visit count 1, do RIGHT JOIN OR HAVING in Group By

SELECT 
    Pe.id AS id, Pe.name AS name, COUNT(v.user_id) number_visit
FROM
    personal Pe
RIGHT JOIN
    visit Vi ON Vi.user_id = Pe.id
GROUP BY Pe.id

OR

SELECT 
    Pe.id AS id, Pe.name AS name, COUNT(v.user_id) number_visit
FROM
    personal Pe
LEFT JOIN
    visit Vi ON Vi.user_id = Pe.id
GROUP BY Pe.id HAVING number_visit > 1


来源:https://stackoverflow.com/questions/14337993/mysql-show-count-of-rows-from-other-table-in-each-row

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!