Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql query with inner join

I have two tables. Something like table1 and table2 given below:
table1 has ID (primary key) and columns Aid, Bid and Cid which are primary key of table 2.

table1

ID  Aid Bid Cid
-----------------
1   X   Y   Z
2   X   Z   Z
3   Y   X   X
-----------------

table2

ID  NAME
------------------
X   Abc
Y   Bcd
Z   Cde
------------------

I want a query which will fetch all columns from table1 this way (after replacing Aid , Bid and Cid with their corresponding names given in table2):

    ID   A   B   C
    1   Abc Bcd Cde
    2   Abc Cde Cde
    3   Bcd Abc Abc

Can you please tell me the mysql query to do this.?

Thank you very much for your answers. But am gettin this when I execute those queries :

+------+------+------+------+
| ID   | A    | B    | C    |
+------+------+------+------+
|    3 | bcd  | abc  | abc  |
|    1 | abc  | bcd  | cde  |
|    2 | abc  | cde  | cde  |
+------+------+------+------+

This query : SELECT * FROM table1 JOIN table2 aa ON table1.Aid = aa.ID JOIN table2 bb ON table1.Bid = bb.ID JOIN table2 cc ON table1.Cid = cc.ID;

gives this result :

+------+------+------+------+------+------+------+------+------+------+
| ID   | Aid  | Bid  | Cid  | ID   | NAME | ID   | NAME | ID   | NAME |
+------+------+------+------+------+------+------+------+------+------+
|    3 | Y    | X    | X    | Y    | bcd  | X    | abc  | X    | abc  |
|    1 | X    | Y    | Z    | X    | abc  | Y    | bcd  | Z    | cde  |
|    2 | X    | Z    | Z    | X    | abc  | Z    | cde  | Z    | cde  |
+------+------+------+------+------+------+------+------+------+------+

I think the query needs to be changed a bit..

like image 888
Anjana Avatar asked Mar 04 '26 18:03

Anjana


1 Answers

This should work:

select table1.ID, a.NAME AS A, b.NAME AS B, c.NAME AS C
from table1 
join table2 a on table1.Aid = a.ID 
join table2 b on table1.Bid = b.ID 
join table2 c on table1.Cid = c.ID

Otherwise:

select table1.ID, a.NAME, b.NAME, c.NAME from table1 join (select * from table2) a on table1.Aid = a.ID join (select * from table2) b on table1.Bid = b.ID join (select * from table2) c on table1.Cid = c.ID
like image 189
Richard Theobald Avatar answered Mar 06 '26 19:03

Richard Theobald



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!