根据结果​​递归查询和更改目标表

时间:2013-03-11 17:37:14

标签: mysql sql select join

假设我有一个类似的查询:

SELECT type_person FROM tbl_event WHERE id_animal = 1;

这给了我一个人的类型和要加入的目标表(在这种情况下,它将返回'worker')从其他表中获取事件的完整数据,现在进行连接我知道我必须做一个加入'工人桌',如:

SELECT  a.*,b.*,z.*
FROM    tbl_event a
        left JOIN tbl_worker b
            ON a.type_person = b.type_person
        left JOIN tbl_animal z
            ON   z.id_animal = a.id_animal 
        WHERE z.id_animal = 1;

有没有办法通过以下方式更改左边JOIN tbl_worker b的部分:

SELECT  a.*,b.*,z.*
FROM    tbl_event a
        left JOIN (SELECT type_person FROM tbl_event WHERE id_animal = 1)
            ON a.type_person = b.type_person
        left JOIN tbl_animal z
            ON   z.id_animal = a.id_animal 
        WHERE z.id_animal = 1;

here is a fiddle

2 个答案:

答案 0 :(得分:1)

当然,你需要做一些事情:

SELECT  a.*,b.*,z.*
FROM    tbl_event a
        left JOIN (SELECT type_person FROM tbl_event WHERE id_animal = 1) as b
            ON a.type_person = b.type_person
        left JOIN tbl_animal z
            ON   z.id_animal = a.id_animal 
        WHERE z.id_animal = 1;

基本上你错过了别名(在这种情况下是b

Here's an updated fiddle

答案 1 :(得分:1)

当然可以。你的意思是那样的

 SELECT  a.*,b.*,z.*
 FROM    tbl_event a
    left JOIN (SELECT type_person FROM tbl_event WHERE id_animal = 1) b
        ON a.type_person = b.type_person
    left JOIN tbl_animal z
        ON   z.id_animal = a.id_animal 
  where z.id_animal = 1;

DEMO

在您的查询中,您忘了制作AS b