0

例如,我有 2 张桌子,一张用于学生/班级,另一张用于学生/兴趣,例如;

studentID   class
---------------------
4134              1
4135              1
4136              1
4137              1
4138              2
4139              2
4140              2
4141              2

studentID   interests
---------------------
4134        basketball
4134        football
4135        basketball
4136        basketball
4137        football
4138        swimming
4138        football
4139        running
4140        tennis
4141        tennis

仅查询哪些学生与他的同学有相同兴趣的最佳方式是什么?最难的部分是 ONLY 的要求。

查询结果不应为 4135、4136、4140 和 4141。由于即使 4134 与 4137 具有相同的兴趣,它们的兴趣都与不属于第 1 类的 4138 相同。

4

1 回答 1

0

我为您的数据创建了两个表 -

CREATE TABLE #temp (id INT , class INT)
CREATE TABLE #temp2 (id INT, activity VARCHAR(500))


INSERT INTO #temp
SELECT 4134 ,             1   UNION ALL
SELECT 4135 ,             1   UNION ALL
SELECT 4136 ,             1   UNION ALL
SELECT 4137 ,             1   UNION ALL
SELECT 4138 ,             2   UNION ALL
SELECT 4139 ,             2   UNION ALL
SELECT 4140 ,             2   UNION ALL
SELECT 4141 ,             2   

INSERT INTO #temp2 SELECT 4134 , 'basketball' UNION ALL SELECT 4134 , 'football' UNION ALL SELECT 4135 , 'basketball' UNION ALL SELECT 4136 , 'basketball' UNION ALL SELECT 4137 , 'football' UNION ALL SELECT 4138 , 'swimming' UNION ALL SELECT 4138 , 'football' UNION ALL SELECT 4139 , 'running' UNION ALL SELECT 4140 , 'tennis' UNION ALL SELECT 4141 , 'tennis'

AND 使用选择语句

    SELECT DISTINCT t.id id
    FROM   #temp2 t
    INNER JOIN #temp2 t1 ON  t.activity = t1.activity AND t.id <> t1.id 
    INNER JOIN #temp t3 ON t.id = t3.id 
    INNER JOIN #temp t4 ON t1.id = t4.id
    WHERE t3.class = t4.class  AND t.id NOT IN (SELECT DISTINCT te.id id 
       FROM   #temp2 te
       INNER JOIN #temp2 te1 ON  te.activity = te1.activity AND te.id <> te1.id 
       INNER JOIN #temp te3 ON te.id = te3.id 
       INNER JOIN #temp te4 ON te1.id = te4.id
       WHERE te3.class <> te4.class)
这将返回 -

id
4135
4136
4140
4141

于 2013-08-06T18:24:19.887 回答