Search code examples
mysqlmysql-8.0

Can i combine these two select queries?


I am using two queries.

First to get tournament_id from a specific userId. The second query gives me information about the treatment itself and the other players in the tournament and their info.

  #Check if `userId` exists in tournaments if found save the value into a variable.

        SELECT 
            tournament_id
        INTO @tournament_id FROM
            tournament_players
        WHERE
            userId = 5324234;


    #Get information about the tournament itself and which (if any) 
     additional users with there info.

        SELECT 
            *
        FROM
            tournaments AS tour
                JOIN
            tournament_players AS tp ON tour.id = tp.tournament_id
                AND tour.id = @tournament_id;

Solution

  • Consider:

    select t.*, tp.*
    from trivia_tournaments.tournaments t
    inner join tournament_players tp on tp.tournament_id = t.id
    where exists (
        select 1
        from tournament_players tp1 
        where tp1.tournament_id = t.id
        and tp1.user_id = ?
    )
    

    This will give you all available information on all tournaments and players to which the user denoted by ? participated.