0

我正在尝试将“users”表中的“userTypeId”与“userRoles”表中的相应“id”相匹配,以便我可以在“userRoles”中回显“roleName”。

以下是表格:

userRoles
---------------------
id  roleName
1   superuser
2   admin
3   editor
4   author
5   contributor
6   subscriber

users
---------------------
id  userName        userTypeId
1   heyjohnmurray   1
2   admin           2

我试过这个查询,每当我检查它时,它都会回显“错误”

$roleQuery = "SELECT id, roleName, userTypeId FROM userRoles JOIN users ON id=userTypeId";
$roleResult = mysqli_query($dbconnect, $roleQuery);

if(!$roleResult){
    echo 'WRONG';
} else {
    echo 'RIGHT';
}
4

2 回答 2

2

ALIAS在桌子上添加一个,

SELECT a.id, a.roleName, b.userTypeId 
FROM   userRoles a, users b
WHERE  a.id = b.userTypeId

或更好地使用格式(ANSI SQL-92

SELECT a.id, a.roleName, b.userTypeId 
FROM   userRoles a
       INNER JOIN users b
          ON a.id = b.userTypeId
于 2012-10-30T03:38:38.717 回答
1

您应该为表使用别名,否则您将在查询中遇到明确的错误,因为两个连接表都有 id,因此服务器可能会被迫在明确的情况下从表中选择字段

 SELECT UR.id, U.roleName, U.userTypeId FROM  userRoles AS UR JOIN users AS U ON UR.id = U.userTypeId
于 2012-10-30T03:50:05.733 回答