3

我有这个查询:

$result3 = mysql_query("SELECT posts.id, posts.date, posts.title, comments.post, comments.id, comments.date FROM posts, comments WHERE posts.id = comments.post")       
or die(mysql_error());  

while($row2 = mysql_fetch_array( $result3 )) {
    echo $row2['title'];
}

问题在于 posts.id 、 posts.date 和 comments.id 、 comments.date 。我怎样才能得到$row2['....];我试过的两张桌子的 id, date$row2['posts.id'];但它没有用!

4

5 回答 5

7

将查询中的列命名(这称为列别名),如下所示:

SELECT 
    posts.id as postsID, 
    posts.date, 
    posts.title, 
    comments.post, 
    comments.id as CommentsID, 
    comments.date 
FROM 
    jaut_posts, 
    f1_comments 
WHERE 
    jaut_posts.id = f1_comments.post

然后你可以使用:

echo $row2['postsID'];
echo $row2['commentsID'];

编辑:

您也可以从我编写并回答的这个问题中受益,该问题讨论了许多常见的 SQL 查询和请求。

于 2012-08-29T11:48:54.530 回答
2

在查询中使用as,例如

select post.id as PostId, comment.id as CommentId

进而 :

row["PostId"]
row["CommentId"]
于 2012-08-29T11:49:30.347 回答
1
while($row2 = mysql_fetch_array( $result3 )) {
  $post_id = $row2[0];
  $posts_date = $row2[1];
  $posts_title = $row2[2];
  $comments_post = $row2[3];
  $comments_id = $row2[4];
  $comments_date = $row2[5];
}
于 2012-08-29T11:49:55.987 回答
1

改变

SELECT posts.id, posts.date, posts.title, comments.post, comments.id, comments.date

进入

SELECT posts.id AS postsid, posts.date, posts.title, comments.post, comments.id AS commentsid, comments.date

然后你可以使用$row2['postsid'];$row2['commentsid'];

于 2012-08-29T11:50:34.363 回答
0

创建别名:

$sql = 'SELECT posts.id AS post_id, comments.id AS comment_id ...';

$row = mysql_fetch_assoc($sql);

echo $row['post_id'];
echo $row['comment_id'];

或者,您可以通过索引访问它(因为您仍然在使用mysql_fetch_array

echo $row[0]; // posts.id
于 2012-08-29T11:49:04.703 回答