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

时间:2012-08-29 11:46:54

标签: php mysql

我有这个问题:

$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'];但它没有用!

5 个答案:

答案 0 :(得分: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'];

编辑:

您也可以从this question I wrote and answered中受益,它讨论了许多常见的SQL查询和请求。

答案 1 :(得分:2)

在查询中使用as,例如

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

然后:

row["PostId"]
row["CommentId"]

答案 2 :(得分: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];
}

答案 3 :(得分: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'];

答案 4 :(得分: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