mysql多列查找

时间:2012-06-02 21:53:47

标签: mysql

尝试从这里的几个表构建一个查询,并在最终确定它时感到困惑:

表1(电路)

t1.circuit_id
t1.circuit_name

(样本数据)

1234, test1
1235, test2
1236, test3

表2(账户)

t2.account_id
t2.account_username

(样本数据)

100, user1
101, user2
102, user3

表3(作业)

t3.circuit_id
t3.assignment1 (references table 2 (account_id))
t3.assignment2 (references table 2 (account_id))
t3.assignment3 (references table 2 (account_id))

(样本数据)

1234, 100, 101, 102
1235, 101, 101, 101
1236, 102, 102, 102

我所追求的是如下结果:

t1.circuit_id, t3.assignment1, t2.account_username, t3.assignment2, t2.account_username, t3.assignment3, t2.account_username.

1234, 100, user01, 101, user02, 102, user03
1235, 101, user02, 101, user02, 101, user02
1236, 102, user03, 102, user03, 102, user03

非常感谢, --a

1 个答案:

答案 0 :(得分:2)

SELECT  t3.circuit_id, t3.assignment1, t21.account_username, t3.assignment2, t22.account_username, t3.assignment3, t23.account_username
FROM    t3
LEFT JOIN
        t2 t21
ON      t21.account_id = t3.assigment1
LEFT JOIN
        t2 t22
ON      t22.account_id = t3.assigment2
LEFT JOIN 
        t2 t23
ON      t23.account_id = t3.assigment3