如果我有多个表格,例如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和评论
有没有办法查询评论和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;
答案 0 :(得分:0)