6
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;

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

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

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

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

4

4 回答 4

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

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

SELECT  p.id, p.name,
        (
        SELECT  COUNT(*)
        FROM    visit v
        WHERE   v.user_id = p.id
        )
FROM    personal p
于 2013-01-15T12:44:07.260 回答
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
于 2013-01-15T12:46:38.447 回答
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;
于 2013-01-15T12:50:12.747 回答
0

这将适用于LEFT JOIN带有.personalvisit

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 JOINOR HAVINGinGroup 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
于 2013-01-15T12:48:38.180 回答