如何从一个表中获取两个列键

时间:2017-03-23 11:40:44

标签: php mysql sql

表1

id name 
1  Av1
2  Av2

表2

id name1 name2
1   1      2

我想根据table1.id喜欢名称,

输出

id name1 name2
1   Av1   Av2

4 个答案:

答案 0 :(得分:3)

试一试:

SELECT table2.id as id, t1_1.name as name1, t1_2.name as name2 FROM table2 table2
LEFT JOIN table1 t1_1  ON table2.name1 = t1_1.id
LEFT JOIN table1 t1_2  ON table2.name2 = t1_2.id

答案 1 :(得分:2)

您需要加入table1两次,例如:

SELECT t2.id, t1.name,t11.name
FROM table2 t2 
INNER JOIN table1 t1  ON t2.name1  = t1.id
INNER JOIN table1 t11 ON t2.name2 = t11.id

答案 2 :(得分:2)

select t2.id, n1.name as name1, n2.name as name2
from table2 t2
    left join table1 n1 on n1.id = t2.name1
    left join table1 n2 on n2.id = t2.name2

答案 3 :(得分:0)

Use below query :

CREATE TABLE #tbl1( Id INT , Name VARCHAR(100))
CREATE TABLE #tbl2(  Id INT , Name1 INT, Name2 INT)

INSERT INTO #tbl1( Id  , Name )
SELECT 1,'Av1' UNION ALL
SELECT 2,'Av2'

INSERT INTO #tbl2( Id  , Name1 , Name2 )
SELECT 1,1,2

SELECT T2.Id , T2.Name , T3.Name
FROM #tbl2 T1
LEFT OUTER JOIN #tbl1 T2 ON T1.Name1 = T2.Id
LEFT OUTER JOIN #tbl1 T3 ON T1.Name2 = T3.Id