如何在MySql中为同一个表名创建两个JOIN?

时间:2011-08-01 11:20:47

标签: mysql join

SELECT table1.name, table2.wage, table2.bonus table3.shift, table3.endtime, table4.vacation
FROM table1
INNER JOIN table2 ON table1.userid = table2.userid
INNER JOIN table3 ON table2.userid = table3.userid
INNER JOIN table3 ON table2.endtime = table3.endtime
INNER JOIN table4 ON table4.userid = table4.userid 
LEFT JOIN table5 ON table1.name = table5.position

这会引发错误:Not unique table/alias: 'table3'

我试过

INNER JOIN table3 tbl3 ON table2.userid = table3.userid
    INNER JOIN tbl3 ON table2.endtime = tbl3.endtime

没法工作

3 个答案:

答案 0 :(得分:2)

给它一个唯一的别名:

SELECT table1.name, table2.wage, table2.bonus t3a.shift, t3b.endtime, table4.vacation
FROM table1
INNER JOIN table2 ON table1.userid = table2.userid
INNER JOIN table3 t3a ON table2.userid = t3a.userid
INNER JOIN table3 t3b ON table2.endtime = t3b.endtime
INNER JOIN table4 ON table4.userid = table4.userid 
LEFT JOIN table5 ON table1.name = table5.position;

实际上,它使更简洁的代码为每个表提供一个别名:

SELECT
    t1.name,
    t2.wage,
    t2.bonus,
    t3a.shift,
    t3b.endtime,
    t4.vacation
FROM table1 t1
INNER JOIN table2 t2 ON t1.userid = t2.userid
INNER JOIN table3 t3a ON t2.userid = t3a.userid
INNER JOIN table3 t3b ON t2.endtime = t3b.endtime
INNER JOIN table4 t4 ON t4.userid = t1.userid 
LEFT JOIN table5 t5 ON t1.name = t5.position;

看起来你在table4的连接中有一个错误,并且选择中缺少逗号 - 我在最后一个版本中更正了它。

答案 1 :(得分:0)

尝试别名表名:

SELECT *
FROM Table1 t1
JOIN Table1 t2
ON t1.X = t2.Y

答案 2 :(得分:0)

使用带有关键字AS的别名(可以省略)。

INNER JOIN table3 AS t31 ON table2.userid = t31.userid
INNER JOIN table3 AS t32 ON table2.endtime = t32.endtime