我有两张桌子,一张是学生/班级和一张桌子。另一个是学生/兴趣,如下所示;
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有相同的兴趣,他们的两个利益都与4138相同,而不是第一类。
答案 0 :(得分: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'
并使用select语句
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