[英]Joined table not returning any results
I successfully joined tables in another part of my code so I followed the same pattern but this time it is not returning any result and I don't understand why.我在代码的另一部分成功加入了表格,所以我遵循了相同的模式,但这次它没有返回任何结果,我不明白为什么。
Here are the tables I am trying to join :这是我尝试加入的表:
- roles - 角色
| id | type |
+----+--------+
| 1 | admin |
| 2 | author |
| 3 | member |
+----+--------+
- users - 用户
+----+----------+-------+----------+-------------------+--------+
| id | username | email | password | role_id | status |
+----+----------+-------+----------+-------------------+--------+
| | | | | 3 (default value) | |
+----+----------+-------+----------+-------------------+--------+
And here is the request :这是请求:
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;
}
SQL should be 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
I've omitted a few of the columns you've defined in the sql you have as I simply don't see the point in them.我省略了您在 sql 中定义的一些列,因为我根本看不出它们的意义。 Not only that but they may seem ambiguous.不仅如此,而且它们可能看起来模棱两可。
For example:例如:
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
Since both 2 tables have id column, it is required to specify which table is referring by <table_name>.id
由于两个表都有 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;
}
Try like this像这样尝试
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.