简体   繁体   中英

How to get single row from a query involving two tables. 2 Foreign Keys are repeated in one entry of child table

I have two tables

1. tbl_clubs
2. tbl_match_schedule

tbl_club has fields;

fld_id | fld_club_name

tbl_match_schedule has fields;

fld_id | fld_club_id_one | fld_club_id_two | fld_match_time.

Now the flow is that admin will 1. go to the add new match schedule. 2. Select the name of club from drop down 1 3. Select the name of the 2nd club (playing against) from drop down 2 4. Give Match time and save.

Now the problem is that I am unable to select the data properly. I need one row, but it gives me two rows when I put the following query

SELECT ms.fld_id, ms.fld_id_club_one , ms.fld_id_club_two , ms.fld_match_time, c.fld_club_name, c.fld_id FROM tbl_match_schedule as ms, tbl_club as c WHERE c.fld_id = ms.fld_id_club_one OR c.fld_id = ms.fld_id_club_two

Please help me, I want something in this form "club name one" vs "club name two" at "19:00"

I am using mysql

If i understand correctly this should do:

SELECT c1.fld_club_name AS 'club_name_one', c2.fld_club_name AS 'club_name_two', s.fld_match_time AS 'at' FROM tbl_match_schedule s
    LEFT JOIN tbl_clubs c1 ON s.fld_club_id_one = c1.fld_id
    LEFT JOIN tbl_clubs c2 ON s.fld_club_id_two = c2.fld_id

Of course you can add a WHERE or ORDER clause after this to suit your further needs as long as you use the c1. and c2. shorthands when you refer to the clubs as the full table name would be ambiguous.

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