我正在尝试将“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';
}
答案 0 :(得分: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
答案 1 :(得分:1)
您应该为表使用别名,否则您将在查询中遇到明确的错误,因为两个连接表都具有id,因此服务器可能会强制要求明确的情况从表中选择字段
SELECT UR.id, U.roleName, U.userTypeId FROM userRoles AS UR JOIN users AS U ON UR.id = U.userTypeId