[英]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.