duanmi4379 2016-11-17 07:38
浏览 18
已采纳

在PHP中选择多个表MYSQL

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. 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

  • 写回答

1条回答 默认 最新

  • duanliangman5398 2016-11-17 07:56
    关注

    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"; 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大