选择匹配两个或更多相关表的记录

时间:2016-04-11 14:42:07

标签: sql sql-server

我有一个'人物'表:

person_id    name

100          jack

125          jill

201          jane

还有许多子表,person_id可以在:

'划船'

id    person_id

1     100

2     201

'游泳'

id    person_id

1     125

2     201

'运行'

id    person_id
1     201

'投掷'

id    person_id

1     125

2     201

我希望能够选择参与两项活动的所有人,无论哪两项活动。

1 个答案:

答案 0 :(得分:1)

正如伟大的@TimSchmelter(伟大的名字)所提到的,你应该真的有一个PersonActivities表,其id与特定活动相对应。

话虽如此,如果你必须使用你当前的架构,一个选项是UNION一起活动表,然后统计哪些人有两个或更多记录,意思是他们参加了两项或更多项活动。

SELECT t1.person_id, t1.name
FROM persons
INNER JOIN
(
    SELECT t.person_id, COUNT(t.person_id) AS activityCount
    FROM
    (
        SELECT person_id FROM rowing
        UNION ALL
        SELECT person_id FROM swimming
        UNION ALL
        SELECT person_id FROM running
        UNION ALL
        SELECT person_id FROM throwing
    ) AS t
    GROUP BY t.person_id
    HAVING COUNT(t.person_id) > 1
) t2
    ON t1.person_id = t2.person_id