简体   繁体   English

在PHP中选择多个表MYSQL

[英]SELECT multiple tables MYSQL in PHP

So this code works only if the tables that I am calling to match the request, however I still want to display all values of the main table which is the news n table. 因此,此代码仅在我要调用的表与请求匹配时才有效,但是我仍然希望显示主表(即news n表)的所有值。 What is the best way to approach this 解决此问题的最佳方法是什么

Here I have just finished my query 在这里,我刚刚完成查询

 $query="SELECT * FROM news n,category c, comments a, appusers u, admins w  WHERE n.cat_id=c.category_id AND w.userId=n.post_author AND  a.post_id=n.id AND u.user_id=a.userID ORDER BY a.commentid DESC, n.id DESC";       
        $result = mysql_query($query);

$json_response = array();
        while($row=mysql_fetch_array($result)) {

            if (!isset($json_response[ $row['id'] ])) {
                $json_response[ $row['id'] ] = [
                'id' => $row['id'],
                'title' => $row['title'],
                'catId' => $row['cat_id'],
                'catName' => $row['category_name'],
                'catImage' => $row['category_image'],
                'postDate' => $row['post_date'],
                'postImage' => $row['post_image'],
                'post' => $row['post'],
                'commentCount' => $row['comment_count'],
                'videoUrl' => $row['video_url'],
                'tags' => $row['tags'],
                'author' => $row['tags'],
                'comments' => [],
                ];
            }
            $json_response[ $row['id']]['comments'][] = [
            'id' => $row['commentid'],
            'comment' => $row['comment'],
            'name' => $row['user_name'],
            'userId' => $row['userID']
            ];
        }

$data = [];
        foreach ($json_response as $element) {
            $data[] = $element;
        }


      echo json_encode($data, JSON_PRETTY_PRINT);

And then I try to display the JSON Result here 然后我尝试在此处显示JSON结果

Please try below query,This may work for you. 请尝试以下查询,这可能适合您。

select * from news n
LEFT JOIN category c ON c.category_id = n.cat_id
LEFT JOIN admins w  ON w.userId=n.post_author
LEFT JOIN comments a ON a.post_id=n.id
LEFT JOIN appusers u ON u.user_id=a.userID 
ORDER BY 
a.commentid DESC, n.id DESC"; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM