Fetch all news and all comments

前端 未结 3 1972
温柔的废话
温柔的废话 2021-01-17 03:33

I\'m trying to code a query that gets all the news and all the comments for each news. My current query is :

SELECT n         


        
3条回答
  •  情话喂你
    2021-01-17 04:09

    You can't do that in one query - best to take the query you've got and post-process the resulting answer to get the data structure you need.

    To elaborate further - any SQL query can only return a two dimensional array of data - one dimension for the columns, and one for the matching rows. In your case what you're actually after is more like a three dimensional table.

    Note also that on your query as written will return all of the news data over and over again for each comment against each article. That's an inefficient use of bandwidth and resource from the database server.

    It's probably more efficient to do it like this (in pseudo-code):

    SELECT * FROM news
    ...
    foreach ($rows as $row) {
      $row['comments] = array();
      $news[$row['id']] = $row;
    }
    
    SELECT * FROM comments
    ...
    foreach ($rows as $row) {
      $news[$row['news_id']]['comments'][] = $row;
    }
    

    The first query gets all of the news articles and puts them in an array. The second query gets the comments, and accumulates a separate array within each news article's structure.

提交回复
热议问题