简体   繁体   中英

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

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. 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

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;
    } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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