简体   繁体   English

如何跨多个连接的行强制执行SQL连接条件?

[英]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. 我不确定这个确切的查询是否适合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()
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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