MySQL 和 PHP - 不是唯一的表/别名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2077355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MySQL & PHP - Not unique table/alias
提问by tEcHnUt
I get the following error listed below and was wondering how do I fix this problem.
我收到下面列出的以下错误,想知道如何解决这个问题。
Not unique table/alias: 'grades'
Here is the code I think is giving me the problem.
这是我认为给我带来问题的代码。
function getRating(){
$dbc = mysqli_connect ("localhost", "root", "", "sitename");
$page = '3';
$sql1 = "SELECT COUNT(*)
FROM articles_grades
WHERE users_articles_id = '$page'";
$result = mysqli_query($dbc,$sql1);
if (!mysqli_query($dbc, $sql1)) {
print mysqli_error($dbc);
return;
}
$total_ratings = mysqli_fetch_array($result);
$sql2 = "SELECT COUNT(*)
FROM grades
JOIN grades ON grades.id = articles_grades.grade_id
WHERE articles_grades.users_articles_id = '$page'";
$result = mysqli_query($dbc,$sql2);
if (!mysqli_query($dbc, $sql2)) {
print mysqli_error($dbc);
return;
}
$total_rating_points = mysqli_fetch_array($result);
if(!empty($total_rating_points) && !empty($total_ratings)){
// set the width of star for the star rating
$rating = (round($total_rating_points / $total_ratings,1)) * 10;
echo $rating;
} else {
$rating = 100;
echo $rating;
}
}
回答by Mark Byers
The problem seems to be here:
问题似乎在这里:
SELECT COUNT(*)
FROM grades
JOIN grades ON grades.id = articles_grades.grade_id
WHERE articles_grades.users_articles_id = '$page'"
You are trying to join the table grades to itself. You probably meant to join with articles_grades.
您正在尝试将表格成绩加入到自身中。您可能打算加入articles_grades。
回答by Sampson
You need to use an alias if you're using the same name twice:
如果您两次使用相同的名称,则需要使用别名:
SELECT FROM grades g1 ...
JOIN grades g2 ON g1.id = g2.grade_id ...
Be sure that you intendedto use the same name twice, and didn't mistakenly enter the same name twice.
确保您打算使用相同的名称两次,并且没有错误地输入两次相同的名称。
回答by sathish
it's saying that because you have table name grades in the query twice
这是因为你在查询中有两次表名成绩
回答by mck89
I thin that in the $sql2 query the second table isn't grades but article_grades. so it will be:
我认为在 $sql2 查询中,第二个表不是成绩而是 article_grades。所以它将是:
"SELECT COUNT(*)
FROM grades
JOIN articles_grades ON grades.id = articles_grades.grade_id
WHERE articles_grades.users_articles_id = '$page'"

