我对这里发生的事情感到困惑。任何人都可以澄清吗?我对SQL很陌生。我知道有4个表(用户,部门,地点,单位)。
function get_info($user)
{
return $this->db->query('SELECT u.*,
d.id AS deptID,
l.id AS locid,
t.UnitName AS unitname FROM users AS u
JOIN departments AS d ON d.id == u.Department
JOIN locations AS l ON l.id == u.Location
JOIN units AS t ON t.id == d.Unit
WHERE u.ID == '.$this->db->escape($user))->result_array();
}
答案 0 :(得分:0)
在$user
中给定用户ID,这将返回用户所在部门的ID(来自d.id = u.Department
),与该部门关联的单位名称(来自t.id = d.Unit
) ,用户所在位置的ID(来自l.id = u.Location
),以及该用户users
表中的所有信息(来自u.*
)。
答案 1 :(得分:0)
它有时可以帮助我理解SQL查询,将它们按部分分组:what,where,how;
选择什么?
SELECT
u.*,
d.id AS deptID,
l.id AS locid,
t.UnitName AS unitname
从哪里选择?:
FROM users AS u
应如何选择?
JOIN departments AS d ON d.id == u.Department
JOIN locations AS l ON l.id == u.Location
JOIN units AS t ON t.id == d.Unit
有关如何选择它的任何进一步规定:
WHERE u.ID == 1
表的别名也令人困惑,我在参考你的查询真正说的内容时写了这个:
*
,真实姓名u
users
)
id
,真实姓名d
中选择departments
,并将其命名为deptID
l
,真实姓名locations
中选择ID,并将其命名为locid
UnitName
,真实姓名t
中选择units
,并将其命名为unitname