简体   繁体   English

mysql将同一个表与另一个表连接

[英]mysql join same table with another table

I have a table name tbl_user 我有一个表名tbl_user 在此处输入图片说明

This table contain a column name db_responsibleid contain the id of the responsible of this person and this person is in this table also example mohammad have db_uid=1 and samir have db_responsibleid=1 this mean that mohammad is responsible for samir 该表包含列名db_responsibleid该列名包含此人的负责人的ID,此人也在该表中,例如mohammad具有db_uid=1和samir具有db_responsibleid=1这意味着mohammad负责samir

also i have another table name tbl_department the table user contain the id of the department on the column name db_udepartment 我也有另一个表名tbl_department ,表用户在列名db_udepartment上包含部门的ID

I try to have the name of the department and the name and the last name of the responsible where db_uid='$id' 我尝试使用部门名称,负责人的姓名和姓氏,其中db_uid='$id'

$id will be getting from url $ id将从URL获取

this is the query that i use 这是我使用的查询

     SELECT 
     user.db_uid,
     user.db_fname,
     user.db_lname,
     user.db_username,
     user.db_pass,
     user.db_email,
     user.db_phone,
     user.db_jobtitle,
     user.db_level,
     user.db_isemployee,
     user.db_responsibleid,
     user.db_companyname,
     user.db_udepartment,
     tbl_department.db_department,
     tbl_department.db_did,
     parent.db_responsibleid,
     parent.db_fname as pfname,
     parent.db_lname as plname,
     parent.db_uid
     from tbl_user as user,tbl_department 
     join tbl_user as parent 
     on 
     user.db_responsibleid=parent.db_uid 
     where 
     user.db_udepartment=tbl_department.db_did 
     and 
     user.db_uid='$id' 

But this query give me this error Unknown column 'user.db_responsibleid' in 'on clause' 但是此查询给我这个错误'on子句'中的未知列'user.db_responsibleid'

How can i solve this problem and get all information with the name of the responsible and the name of the department ?? 我该如何解决此问题,并获得包含负责人姓名和部门名称的所有信息?

You can not mix implizit and explizit join. 您不能混合使用隐式联接和显式联接。 If you decided to use join you have to do it everywhere: 如果决定使用join,则必须在所有地方都使用它:

from tbl_user as user
 join tbl_department on user.db_udepartment=tbl_department.db_did 
 join tbl_user as parent 
 on 
 user.db_responsibleid=parent.db_uid 
 where 
 user.db_uid='$id' 

Hint: use prepared Statements to prevent SQL-injection 提示:使用准备好的语句来防止SQL注入

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM