如何显示具有相似列的两个Mysql表中的值。

时间:2015-01-17 09:48:24

标签: php mysql pdo

美好的一天,我选择了两个MySQL表格和成员,但这两个表有类似的字段叫做'id',现在,我想选择'tcomment'表的id,而不是'成员的id' '表出现了。我该怎么做呢?这是下面的代码。

<?php

              $comment= "SELECT c.*, m.* FROM tcomment c JOIN members m ON c.poster = m.id WHERE comment_id = :id";   

foreach ($db->query($comment, array('id' => $_GET['id'])) AS $tresult){

             echo  "{$tresult['id']}";
    }

?>

2 个答案:

答案 0 :(得分:0)

您可以在SQL查询中使用aliases;

示例代码

 $comment= "SELECT c.*, c.id as comment_id, m.*, m.id as member_id FROM tcomment c JOIN members m ON c.poster = m.id WHERE comment_id = :id"; 

答案 1 :(得分:0)

正如@u_mulder所说,应用别名

$comment =<<<ccc
    SELECT c.id AS 'idWanted', c.*, m.*
    FROM tcomment c JOIN members m ON c.poster = m.id
    WHERE comment_id = :id
ccc;

foreach ($db->query($comment, array('id' => $_GET['id'])) AS $tresult){

         echo  "{$tresult['idWanted']}";
}