开发者

How do I enforce SQL join conditions across multiple joined rows?

Suppose you have a database schema with tournaments related to games. A tournament may have many games.

I'm trying to join tournaments to games and only pull back tournaments with all games in the future.

SELECT DISTINCT tournaments.*
FROM tournaments
INNER JOIN games ON tournaments.game_id = games.id
WHERE games.event_date >= NOW();

There are a few more tables I'm joining against, but I've simplified it for the sake of this example.

My query is pulling back results where not all of the games in the tournament are in the future.

I have also tried moving the condition into the join:

SELECT DISTINCT tournaments.*
FROM tournaments
INNER JOIN games ON (tournaments.game_id = games.id AND games.event_date >= NOW())

but i get the same result.

How do I make sure that all of the tournaments returned have games in the future - that is, enforce the condition across all rows joined wit开发者_运维技巧h?

Thanks!


I'm not sure if this exact query is appropriate for MySQL. But the idea should work -- for each tournament, determine the earliest game date, and return only the tournaments for which that date is greater than now.

SELECT * from tournaments
WHERE id IN
( SELECT tournaments.id
  FROM tournaments INNER JOIN games ON tournaments.game_id = games.id
  GROUP BY tournaments.id
  HAVING MIN(games.event_date) >= now()
)


SELECT DISTINCT tournaments.*
    FROM tournaments
        INNER JOIN games 
            ON tournaments.game_id = games.id
                AND games.event_date >= NOW()
    WHERE NOT EXISTS (SELECT NULL FROM games g2 WHERE g2.id = tournaments.game_id AND g2.event_date < NOW())


maybe something like this:

SELECT DISTINCT t.* 
FROM tournaments t, (select id, event_date from games where event_date >= now() ) g
where t.game_id = g.id 


Try this

SELECT DISTINCT *
FROM tournaments 
where game_id in (
Select id from games where event_date >= NOW()
)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜