我成功地将表连接到了代码的另一部分,所以我遵循相同的模式,但是这次它不返回任何结果,我也不明白为什么。
这是我要加入的表:
-角色
| id | type |
+----+--------+
| 1 | admin |
| 2 | author |
| 3 | member |
+----+--------+
-用户
+----+----------+-------+----------+-------------------+--------+
| id | username | email | password | role_id | status |
+----+----------+-------+----------+-------------------+--------+
| | | | | 3 (default value) | |
+----+----------+-------+----------+-------------------+--------+
这是请求:
public function get_users()
{
$users_list = $this->dbh->query('SELECT users.id, roles.id AS roleid, type, role_id, id, username FROM users LEFT JOIN roles ON users.role_id = roles.id ORDER BY id ASC');
return $users_list;
}
答案 0 :(得分:0)
SQL应该是
SELECT
u.id,
r.id AS roleid,
u.type,
r.username
FROM users u
LEFT JOIN roles r ON r.id = u.role_id
ORDER BY u.id ASC
我已经省略了在sql中定义的一些列,因为我根本看不到它们的要点。不仅如此,而且它们似乎模棱两可。
例如:
SELECT
users.id, // User ID
roles.id AS roleid, // Role ID
type, // User type
role_id, // Role ID (We already have it, no need for it again)
id, // What ID? This is ambiguous and will fail
username // User Username
答案 1 :(得分:0)
由于两个表都具有id列,因此需要指定<table_name>.id
所引用的表
public function get_users()
{
$users_list = $this->dbh->query('SELECT users.id AS userid, roles.id AS roleid, type, role_id, username FROM users LEFT JOIN roles ON users.role_id = roles.id ORDER BY users.id ASC');
return $users_list;
}
答案 2 :(得分:0)
尝试这样
public function get_users()
{
$users_list = $this->dbh->query('SELECT u.id AS userid, r.id AS roleid, r.type, u.role_id, u.username FROM users as u LEFT JOIN roles as r ON u.role_id = r.id ORDER BY u.id ASC');
return $users_list;
}