【问题标题】:Multiple Queries and Easy Output (PDO?)多查询和轻松输出 (PDO?)
【发布时间】:2012-01-10 04:08:29
【问题描述】:

如果我有多个表,例如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 和 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;

【问题讨论】:

    标签: php mysql database pdo


    【解决方案1】:

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

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

    SELECT * FROM table_a
    UNION
    SELECT * FROM table_b
    

    【讨论】:

    • 我并不是说不使用它。使用它。我只是说这是一个 SQL 问题,而不是 PDO。我试图让您专注于问题的 SQL 部分,而不是专注于 PDO。
    • 你能举个简单的例子吗?我会做类似("SELECT * FROM table_a WHERE id=$id UNION SELECT * FROM table_b WHERE id=$id") 之类的事情吗?
    • 我做对了吗?我试过了,但我收到了 Call to a member function fetchObject() on a non-object?
    猜你喜欢
    • 2012-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多