在MySQL中选择用户和COUNT个共享项

时间:2016-09-12 16:53:41

标签: php mysql

我有一个用户表

enter image description here

一张表"共享"事件

enter image description here

如果我是斯科特(ID = 1),我如何选择分享我的活动的用户并添加一个特殊列,其中包含关闭共享事件的数字

enter image description here

----求助----

这两个查询完成了这项工作:

感谢 user6368519

SELECT
    t2.ID,
    t2._name,
    t2._email,
    COUNT(*) _shared
FROM _user_events t1 
INNER JOIN _users t2 ON ( t1._user = t2.id )
WHERE _event IN ( SELECT _event FROM _user_events t3 WHERE t3._user = 1 )
AND t1._user <> 1
GROUP BY 1,2

感谢 S.加尔塞斯

SELECT
    users.ID,
    users._name,
    users._email,
    (
        SELECT COUNT(*)
        FROM _user_events
        WHERE _user = users.ID
        AND _event IN (
            SELECT _event FROM _user_events WHERE _user = 1
        )
    ) as _shared
FROM _users users
WHERE ID != 1
AND ID IN (
    SELECT _user
    FROM _user_events
    WHERE _event IN (
        SELECT _event FROM _user_events WHERE _user = 1
    )
)

3 个答案:

答案 0 :(得分:1)

试试这个:

SELECT user.ID, user._name user._email, 
(SELECT count(*) FROM shared_event where _user = user.id and _event in
  (SELECT _event from shared_event where _user = 1)
) as _shared
FROM USER WHERE ID != 1

答案 1 :(得分:1)

如果您不介意单个MySQL语句:

SELECT t1._user ID,t2._name,t2._email,COUNT(*) _shared
    FROM shared t1 INNER JOIN user t2 ON (t1._user=t2.id)
    WHERE _event IN (SELECT _event FROM shared t3 WHERE t3._user=1)
        AND t1._user<>1
    GROUP BY 1;

答案 2 :(得分:0)

尝试在共享上使用自联接并与用户表联接,如:

SELECT id, name, email, id
FROM users u INNER JOIN
    (SELECT DISTINCT s2._user
    FROM shared s1 INNER JOIN Shared s2
    ON s1._event = s2._event
    WHERE s1._user = 1) temp
ON u.id = temp.user