简体   繁体   中英

Mysql:multiple join in one table

I have a database and inside database are table with joins.

My first table is cardtests the columns are id and name only. I joined it in tests my columns are :

card1_id | card2_id | card3_id

in which they are equal to cardtests.id.

My sqlquery is

SELECT cardtests.name 
  FROM tests 
  JOIN cardtests 
  ON tests.card1_id = cardtests.id
  ON tests.card2_id = cardtests.id
  ON tests.card3_id = cardtests.id

But the problem is they are not working just wanted to display all the names of 3 cards. How will i do it thanks.

Select cardtests.name 
from tests 
join cardtests on cardtests.id in (tests.card1_id, tests.card2_id, tests.card3_id)

I think you want three joins:

Select ct1.name, ct2.name, ct3.name
from tests t left join
     cardtests ct1
     on t.card1_id = ct1.id left join
     cardtests ct2
     on t.card2_id = ct2.id left join
     cardtests ct3
     on t.card3_id = ct3.id;

The left join simply handles rows where one or more of the card test columns may not be populated.

Often, though, having multiple columns with the same name, only distinguished by a number, is an indication that you should be using a separate table, with one row per tests and card.

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