多个查询和轻松输出(PDO?)

时间:2012-01-10 04:08:30

标签: php mysql database pdo

如果我有多个表格,例如commentsuser_comments,我将如何一次查询这些表格?

通常当我有一个表可供选择时,我通常会这样做:

$query = $db->query("SELECT * FROM comments");
while($q = $query->fetchObject()){
     $id = $q->id; //getting the id from comments table only
     $text = $q->comment; //getting the comments from comments table only
}

这给了我id和评论

有没有办法查询评论和user_comments?也许它会像这样

$id= $q -> comments -> id;//getting the id from comments table
$text = $q -> comments -> comment;//getting comment from comments table
$user_id = $q -> user_comments -> id;//getting the id from user_comments
$user_text = $q -> user_comments -> comments;//getting the comments from user_comments

这将允许我轻松地从不同的表中获取值,无论它们是否在每个表中具有相同的列名。

这可能吗?

由于

编辑:试试?

$sql = $dbh->query("SELECT * FROM comments WHERE id=4 UNION SELECT * FROM user_comments WHERE id=1");
$q = $sql->fetchObject();
$name = $q->comments->username;
$text = $q->user_comments->comments;
echo $name;
echo $text;

1 个答案:

答案 0 :(得分:0)

对于这个特定的练习,请忘记PDO并专注于SQL。

您可以使用UNION聚合两个表。

SELECT * FROM table_a
UNION
SELECT * FROM table_b