SQL从其他表中获取id的名称

时间:2016-01-30 17:19:22

标签: mysql

我有两张桌子:

1.Table1

---------------------------------
| id_table1 | id_test1| id_test2|
---------------------------------
| 1         | 10      | 1       |
---------------------------------
| 2         | 20      | 3       |
---------------------------------

2.Table2

-------------------
| id_table2 | name|
-------------------
| 1         |name1| 
-------------------
| 3         |name3|  
-------------------
| 10        |name10| 
-------------------
| 20        |name20| 
-------------------

id_test1id_test2与table2有关系,我只想查询name,例如

-------------------
| NameA     |NameB|
-------------------
| name10    |name1| 
-------------------
| name20    |name3| 
-------------------
在PHP中

我可以解决循环但我只想在SQL中解决这个问题。

2 个答案:

答案 0 :(得分:1)

应该是这个查询

select a.name, b.name 
from table2 as a, 
inner join table2 as b
inner join table1 as c
where c.id_test1 = a.id_table2
and c.id_test2 = b.id_table2;

答案 1 :(得分:0)

SELECT a.name b.name FROM " + table2 +" a JOIN "+ table1 + " z ON a.id_table2 = z.id_test1 WHERE a.name ="+ "'"+given_ID(id_test1)+"'" and b.name ="+ "'"+given_ID(id_test2)+"'";