从两个表中选择相同的列名


Select same column name from two tables

我有这个查询:

$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上。我怎么能得到这两个表的id和日期$row2['....];我试过$row2['posts.id'];,但它不起作用!

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

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查询和请求。

在查询中使用as,类似

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

然后:

row["PostId"]
row["CommentId"]
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];
}

更改

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'];

创建别名:

$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