[英]Mysql How to join 2 tables and 1 table itself
I have a table name tbl_user
this table contain 我有一个表名
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
The other table is tbl_task
this table contain 另一个表是
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
Now i want to have this result: 现在我想得到这个结果:
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
this result to select all task that have db_status='Done'
and db_emailed='0'
with the name of the user and the name of the responsible of that user with the email of the responsible 此结果选择具有
db_status='Done'
和db_emailed='0'
所有任务,并带有用户名和该用户的负责人的名称以及负责人的电子邮件
I use this query but i can't get the name of the responsible and his email address 我使用此查询,但无法获取负责人的姓名和他的电子邮件地址
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')
Current result is: 当前结果是:
taskid mytask desc Status staffname responsiblename remail
1 test test Done ttt eee NULL NULL
2 bnvc sdcs Done ggg hhh NULL NULL
How can i solve this problem any suggestion or help ?! 我如何解决这个问题有任何建议或帮助?
You join the wrong columns on the second left join (i have use user1 and use2 alias for the two join on tbl_user) 您在第二个左联接上联接了错误的列(我在tbl_user上为两个联接使用了user1和use2别名)
you use user.db_uid=user.db_responsibleid
but should tbl_user.db_uid=user.db_responsibleid
您使用
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'
You can try this query. 您可以尝试此查询。 Check if it meets your requirements
检查是否符合您的要求
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.