mysql显示每行中其他表的行数

时间:2013-01-15 12:42:33

标签: mysql select count

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;

我试图让所有用户及他们所做的访问次数。

我得到的结果是所有用户,但count列包含相同的值(不是特定于该行ID)。

我在这里做错了什么?如何告诉mysql用户这行id?

是复合选择最佳方式还是有更好的方法?

4 个答案:

答案 0 :(得分:20)

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

您当然也可以使用subselect(例如,如果您有ANSI GROUP BY兼容性):

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

答案 1 :(得分:2)

试试这个

 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

答案 2 :(得分:1)

试试这个:

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;

答案 3 :(得分:0)

这适用于LEFT JOINpersonalvisit

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

如果您只想让至少访问次数为1的用户,请RIGHT JOIN中的HAVINGGroup 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

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