简体   繁体   中英

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 with?

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()
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM