简体   繁体   中英

I want a better way of writing SQL that gets all comments from comments table, belonging to a particular article in articles table

I have an articles table with PK_articleid, and comments table with FK_articleid which references the articles table. I want to be able to get all the comments that belong to a particular article. See table below:

文章表

评论表

So far, i am able to get required columns with INNER JOIN, but i want a way to access the comments object properties like in the "What i want" sample object below.

const text = 'SELECT a.articleid, a.createdon, a.title, a.article, c.id, c.comment, c.authorid  
FROM articles a INNER JOIN comments c ON a.articleid = c.articleid';

    exports.getArticleAndComments = (request, response) => {

      pool.query(text, (error, res) => {
        if (error) {
          // throw error
          console.log(`not able to get connection ${error}`);
          response.status(400).json({
            status: 'error',
            error: error.stack,
          });
        }
        response.status(200).json({
          status: 'success',
          data: {
            id: res.rows[0].articleid,
            createdon: res.rows[0].createdon,
            title: res.rows[0].title,
            article: res.rows[0].article,
            comments: res.rows
          },
        });
      });
    };

What i want:

"data" : {
    "id" : Integer ,
    "createdOn" : DateTime ,
    "title" : String ,
    "article" : String ,
    "comments" : [
      {
        "commentId" : Integer ,
        "comment" : String ,
        "authorId" : Integer ,
      } ,
      {
        "commentId" : Integer ,
        "comment" : String ,
        "authorId" : Integer ,
      } ,
    ]
  }

What i get:

{
  "status": "success",
  "data": {
    "id": 21,
    "createdon": "2019-11-13T19:41:51.613Z",
    "title": "The gods must be crazy",
    "article": "An article about crazy gods",
    "comments": [
      {
        "articleid": 21,
        "createdon": "2019-11-13T19:41:51.613Z",
        "title": "The gods must be crazy",
        "article": "An article about crazy gods",
        "commentId": 28,
        "comment": "The gods have always been crazy",
        "authorid": 106
      },
      {
        "articleid": 21,
        "createdon": "2019-11-13T19:41:51.613Z",
        "title": "The gods must be crazy",
        "article": "An article about crazy gods",
        "commentId": 27,
        "comment": "Unleash the dragon",
        "authorid": 106
      }
    ]
  }
}

From what i understand, you need to get the table attributes not the stored data. In postgres, the way to get table attributes(col names & data types) is to query the information schema as per there docshttps://www.postgresql.org/docs/current/infoschema-columns.html

Not the best way of doing it but the closest to your code (so, less changes)

const text = 'SELECT a.articleid, a.createdon, a.title, a.article, c.id, c.comment, c.authorid  
FROM articles a INNER JOIN comments c ON a.articleid = c.articleid
WHERE a.articleid = YOUR_ARTICLE_ID_HERE';

exports.getArticleAndComments = (request, response) => {

  pool.query(text, (error, res) => {
    if (error) {
      // throw error
      console.log(`not able to get connection ${error}`);
      response.status(400).json({
        status: 'error',
        error: error.stack,
      });
    }
    response.status(200).json({
      status: 'success',
      data: {
        id: res.rows[0].articleid,
        createdon: res.rows[0].createdon,
        title: res.rows[0].title,
        article: res.rows[0].article,
        comments: res.rows.map((row) => {return {
          commentId: row.commentId,
          comment: row.comment,
          authorId: row.authorId,
        }})
      },
    });
  });
};

You said you want the info that "belong to a particular article", replace the article id at the end of the query for that (YOUR_ARTICLE_ID_HERE).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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