我该如何执行以下SQL搜索?

时间:2011-03-09 08:40:14

标签: sql

假设以下架构

user_id, tournament_id, round

如何在tournament_id = 26,round = 8但不在tournament_id = 26,round = 7中进行搜索以查找用户。

用户对tournament_id = 26,round = 8

有一行

tournament_id = 26,round = 7

的零行

我已经尝试过了

where user_id not in (select ... where tournament_id=26 and round=7)

但是很慢

3 个答案:

答案 0 :(得分:1)

SELECT user_id
FROM tournaments
WHERE tournament_id = 26
  AND [round] = 8

EXCEPT

SELECT user_id
FROM tournaments
WHERE tournament_id = 26
  AND [round] = 7

或使用中间表:

SELECT user_id, [round]
INTO tournament26
FROM tournaments
WHERE torunament_id = 26;

SELECT user_id
FROM tournament26
WHERE [round] = 8

EXCEPT

SELECT user_id
FROM tournament26
WHERE [round] = 7

在SQL Server中,您可以使用CTE而不是中间表:

WITH tournament26 AS (
  SELECT user_id, [round]
  FROM tournaments
  WHERE tournament_id = 26
)
SELECT user_id
FROM tournament26
WHERE [round] = 8

EXCEPT

SELECT user_id
FROM tournament26
WHERE [round] = 7

答案 1 :(得分:0)

工作示例:

CREATE TABLE #t 
(
[user_id] INT, 
tournament_id INT, 
[round] INT
)

INSERT INTO #t
SELECT 1, 26, 8
UNION SELECT 1, 26, 7
UNION SELECT 2, 26, 7
UNION SELECT 3, 26, 7
UNION SELECT 4, 26, 8
UNION SELECT 4, 25, 8
UNION SELECT 4, 25, 7

SELECT user_id, tournament_id, MAX(round), COUNT(1)
FROM   #t
WHERE  tournament_id=26
GROUP BY user_id, tournament_id
HAVING COUNT(1) = 1 AND MAX(round) = 8

答案 2 :(得分:-1)

我假设您还有一个用户表?

试试这个:

select * from users u
join tournament t on t.user_id = u.id
where t.tournament_id=26 and t.round=8