我有两张桌子。下面给出了table1和table2之类的东西:
table1具有ID(主键)和列Aid,Bid和Cid,它们是表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
------------------
我想要一个查询,以这种方式从table1中获取所有列(在用表2中给出的相应名称替换Aid,Bid和Cid之后):
ID A B C
1 Abc Bcd Cde
2 Abc Cde Cde
3 Bcd Abc Abc
你能告诉我mysql查询吗?
非常感谢您的回答。但是当我执行这些查询时,我会开始这样做:
+------+------+------+------+
| ID | A | B | C |
+------+------+------+------+
| 3 | bcd | abc | abc |
| 1 | abc | bcd | cde |
| 2 | abc | cde | cde |
+------+------+------+------+
此查询: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;
给出了这个结果:
+------+------+------+------+------+------+------+------+------+------+
| 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 |
+------+------+------+------+------+------+------+------+------+------+
我认为查询需要稍微修改一下..
答案 0 :(得分:3)
这应该有效:
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
否则:
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
答案 1 :(得分:2)
你可以试试这个。 INNER JOIN
& ORDER
-
SELECT a.ID, b.NAME, c.NAME, d.NAME
FROM table1 a
INNER JOIN table2 b ON b.ID = a.Aid
INNER JOIN table2 c ON c.ID = a.Bid
INNER JOIN table2 d ON d.ID = a.Aid
ORDER BY a.ID
答案 2 :(得分:1)
SELECT table1.ID, aa.NAME A, bb.NAME B, cc.NAME C
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
答案 3 :(得分:1)
这应该适合你:
SELECT t1.ID, t2a.NAME as A, t2b.NAME as B, t2c.NAME as C
from table1 t1
INNER JOIN table2 t2a ON t1.Aid = t2a.ID
INNER JOIN table2 t2b ON t1.Bid = t2b.ID
INNER JOIN table2 t2c ON t1.Cid = t2c.ID
ORDER BY t1.ID ASC
答案 4 :(得分:1)
你可以尝试以下查询,因为我已经用我的mysql手动检查了它:
SELECT ID,(SELECT NAME FROM table2 as t2 WHERE t1.Aid=t2.ID) as A,(SELECT NAME FROM table2 as t2 WHERE t1.Bid=t2.ID) as B,(SELECT NAME FROM table2 as t2 WHERE t1.Cid=t2.ID) as C FROM table1 AS t1
由于
答案 5 :(得分:1)
您可以使用以下查询来获得所需的结果:
SELECT t1.ID AS ID, a.NAME AS A, b.NAME AS B, c.NAME AS C FROM (table1 t1, table2 a, table2 b, table2 c) WHERE (t1.Aid = a.ID AND t1.Bid = b.ID AND t1.Cid = c.ID) ORDER BY t1.ID;