简体   繁体   中英

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

I have a mysql database that has two tables:

GAME (ID, Name)

TICKET (ID, GameID, Section...)

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.

I have the sql statement:

SELECT * FROM GAME ORDER BY Date

It returns all game records from the GAME table. 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.

I've tried joining the tables together and checking it that way, but my sql just isn't there yet.

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.

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  

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