【发布时间】:2012-01-10 04:08:29
【问题描述】:
如果我有多个表,例如comments 和user_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 和 cmets
有没有办法查询 cmets 和 user_cmets?也许就这样
$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;
【问题讨论】: