繁体   English   中英

这个JOIN有什么问题?

[英]What's wrong with this JOIN?

我试图将“ 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';
}

在表格上添加一个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

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

 SELECT UR.id, U.roleName, U.userTypeId FROM  userRoles AS UR JOIN users AS U ON UR.id = U.userTypeId

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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