简体   繁体   English

检查一个表的ID是否用作另一个表的外键

[英]Check if the ID of one table is used as a foreign key in another

I have a mysql database that has two tables: 我有一个具有两个表的mysql数据库:

GAME (ID, Name) 游戏(ID,名称)

TICKET (ID, GameID, Section...) 门票(ID,GameID,部分...)

Game.ID is a primary key in GAME, and GameID is used in the TICKET table as a foreign key to know which game it is part of. Game.ID是GAME中的主键,GameID在TICKET表中用作外键,以了解它属于哪个游戏。

I have the sql statement: 我有sql语句:

SELECT * FROM GAME ORDER BY Date 选择*从游戏订购日期

It returns all game records from the GAME table. 它从GAME表返回所有游戏记录。 I want a sql statement that will only return the game record if there is at least 1 record using it as a foreign key in the TICKET table, thus only giving me the games that have tickets. 我想要一个sql语句,如果在TICKET表中有至少1条记录用作外键,则该语句仅返回游戏记录,因此只给我有票证的游戏。

I've tried joining the tables together and checking it that way, but my sql just isn't there yet. 我尝试将表连接在一起并以这种方式进行检查,但是我的sql尚不存在。

Thanks in advance for any help you can give me. 预先感谢您可以给我的任何帮助。

SELECT * FROM GAME
JOIN TICKET ON GAME.ID = TICKET.GameID
GROUP BY Game.ID
ORDER BY Date
select * from game g inner join ticket t on g.id = t.game_id

That will return one row per ticket (5 tickets to one game will become 5 rows here)...uses an 'inner join' as a filter. 每张票将返回一行(一场比赛的5张票将在此处变成5行)...使用“内部联接”作为过滤器。

I suspect you are looking for something more like 我怀疑您正在寻找更像的东西

Select * from game where id in (select game_id from ticket group by game_id)

This will give you one row per game regardless of number of tickets. 无论门票数量多少,这将使您每场比赛获得一排。

Let's get fancy 让我们看上

SELECT * FROM GAME G
WHERE EXISTS
    (
    SELECT 1
    FROM TICKET T
    WHERE G.ID = T.GameID
    )
SELECT * FROM GAME ,TICKET   where TICKET.GameID  = GAME.ID ORDER BY Date  

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

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