Mysql如何连接2个表和1个表本身

时间:2017-08-11 08:00:21

标签: php mysql

我有一个表名tbl_user,此表包含

db_uid   db_fname   db_lname   db_responsibleid     db_email
  1         xxx       yyy            0             xxx@x.com
  2         ttt       eee            1             ttt@x.com
  3         ggg       hhh            2             ggg@x.com

另一个表格tbl_task此表包含

db_taskid    db_mytask    db_desc   db_status   db_emailed   db_userid
   1           test       test        Done          0           2
   2           bnvc       sdcs        Done          0           3
   3           bcv        sdc         Scheduled     0           3

现在我希望得到这样的结果:

  taskid   mytask   desc   Status   staffname   responsiblename    remail
    1       test    test   Done      ttt eee      xxx yyy        xxx@x.com
    2       bnvc    sdcs   Done      ggg hhh      ttt eee        ttt$x.com

此结果可选择包含db_status='Done'db_emailed='0'的所有任务 使用负责人

的电子邮件,用户名和负责该用户的姓名

我使用此查询但我无法获取负责人及其电子邮件地址的名称

select 
    tbl_task.db_mytask,
    tbl_task.db_desc,
    tbl_task.db_taskid,
    tbl_task.db_status,
    concat(tbl_user.db_fname,' ' ,tbl_user.db_lname) as name,
    concat(user.db_fname,' ' ,user.db_lname) as uname,
    user.db_email
from tbl_task 
left join tbl_user
    on tbl_task.db_userid=tbl_user.db_uid
left join tbl_user as user
    on user.db_uid=user.db_responsibleid
where 
    (tbl_task.db_emailed='0') 
    and 
    (tbl_task.db_status='Done')

目前的结果是:

taskid   mytask   desc   Status   staffname   responsiblename    remail
  1       test    test   Done      ttt eee        NULL             NULL
  2       bnvc    sdcs   Done      ggg hhh        NULL             NULL

如何解决这个问题的任何建议或帮助?!

2 个答案:

答案 0 :(得分:3)

你在第二个左连接上加入了错误的列(我在tbl_user上使用了user1和use2别名进行了两次连接)

您使用的是user.db_uid=user.db_responsibleid,但tbl_user.db_uid=user.db_responsibleid

  select 
    tbl_task.db_mytask,
    tbl_task.db_desc,
    tbl_task.db_taskid,
    tbl_task.db_status,
    concat(user1.db_fname,' ' ,user1.db_lname) as name,
    concat(user2.db_fname,' ' ,user2.db_lname) as uname,
    user2.db_email
  from tbl_task 
  left join tbl_user as user1 on tbl_task.db_userid=user1.db_uid
  left join tbl_user as user2 on user2.db_uid=user1.db_responsibleid
  where tbl_task.db_emailed='0'
  and tbl_task.db_status='Done'

答案 1 :(得分:2)

您可以尝试此查询。 检查它是否符合您的要求

select
    tbl_task.db_taskid,
    tbl_task.db_mytask as mytask, 
    tbl_task.db_desc,    
    tbl_task.db_status,
    concat(tbl_user.db_fname,' ' ,tbl_user.db_lname) as name,
    concat(users.db_fname,' ' ,users.db_lname) as responsiblename, 
    users.db_email as remail
from tbl_user AS users 
    RIGHT OUTER JOIN tbl_user ON users.db_uid = tbl_user.db_responsibleid 
    RIGHT OUTER JOIN tbl_task ON tbl_user.db_uid = tbl_task.db_userid
where  (tbl_task.db_emailed='0') and (tbl_task.db_status='Done')