0

我想使用多个表来获取最近的帖子(Q)和用户名(句柄),但是当我尝试使用此代码时,它给出了错误

表名qa_postsqa_users需要连接来自qa_posts的userid处理来自qa_users

SELECT *
FROM qa_posts, qa_users
WHERE type="Q" AND qa_posts.userid = "qa_users.handle"
ORDER BY created DESC
LIMIT 5

错误信息

SELECT *
FROM qa_posts, qa_users
WHERE qa_posts.userid = "qa_users.handle"
ORDER BY created DESC
LIMIT 5

Error 1052: Column 'created' in order clause is ambiguous

实际代码

qa_db_connection();
$query_post = qa_db_query_raw('         
    SELECT *
    FROM qa_posts, qa_users
    WHERE type="Q" AND qa_posts.userid = "qa_users.handle"
    ORDER BY created DESC
    LIMIT 5

') or die(mysql_error());

while($row = mysql_fetch_array($query_post)) {
    echo $row['title'];
    echo '<span style="font-size:65%;font-style:italic">'.$row['created'].'</span>';
    echo '<br/>';
}

有关表结构,请参阅此图像 表结构

4

2 回答 2

1

该错误告诉您有多个具有名称的列,created因此您需要指定该created字段来自哪个表以执行ORDER BY

SELECT *
FROM qa_posts, qa_users
WHERE qa_posts.userid = "qa_users.handle"
ORDER BY qa_posts.created DESC
LIMIT 5

或者:

SELECT *
FROM qa_posts, qa_users
WHERE qa_posts.userid = "qa_users.handle"
ORDER BY qa_users.created DESC
LIMIT 5

编辑#1,没有看到完整的表结构,看起来你可能想要这样做,你有qa_users.handle引号,这些可能应该被删除:

SELECT *
FROM qa_posts
INNER JOIN qa_users
   ON qa_posts.userid = qa_users.handle
ORDER BY qa_posts.created DESC
LIMIT 5

编辑#2 你加入了错误的领域:

SELECT *
FROM qa_posts
INNER JOIN qa_users
   ON qa_posts.userid = qa_users.userid
WHERE qa_posts.type="Q" 
ORDER BY qa_posts.created DESC
LIMIT 5
于 2012-09-08T17:57:27.373 回答
1

当您在两个表中都有相同的名称列时,会出现给定的错误......因此您必须指定列名以及表名,如下面的模式:

table_name.column_name

所以,你的查询应该是这样的:

SELECT *
FROM qa_posts, qa_users
WHERE qa_posts.userid = "qa_users.handle"
ORDER BY qa_posts.created DESC (or put the ORDER BY qa_users.created DESC if you want to make order by `created` of `qa_users` )
LIMIT 5

如果您真的不希望拥有值为“qa_users.handle”的用户 ID,则不应引用它们并且应该进行如下查询:

    SELECT *
    FROM qa_posts, qa_users
    WHERE qa_posts.userid = qa_users.userid AND qa_posts.type="Q" 
    ORDER BY qa_posts.created DESC 
    LIMIT 5

您最好通过以下方式使用 JOIN:

    SELECT *
    FROM qa_posts INNER JOIN qa_users ON qa_posts.userid = qa_users.userid 
    WHERE qa_posts.type="Q" 
    ORDER BY qa_posts.created DESC 
    LIMIT 5
于 2012-09-08T17:59:50.677 回答