使用Node.js查询连接两个Postgres数据库表

时间:2018-11-26 11:41:42

标签: node.js postgresql azure

在尝试将JOIN语句添加到下面的查询语句中并删除“ JOIN table_name2”后,我一直在遇到iisnode时遇到错误,然后该查询有效。如何修正该语句以使其生效?有什么建议吗?

const getUserById = (request, response) => {
  const id = parseInt(request.params.id)

  pool.query('SELECT * FROM table_1 JOIN table_2 WHERE "GTIN" = $1', [id], (error, results) => {
    if (error) {
      throw error
    }
    response.status(200).json(results.rows)
  })
} 

表1

      GTIN     |      gtinName  
--------+----------------+---------
26001087006846 |    Product Name

表2

      GTIN      |    nutrientTypeCode  
--------+-------------------+------------
 26001087006846 |        Protein
--------+-------------------+------------
 26001087006846 |         Energy

所需结果

      GTIN     |    gtinName      |    nutrientTypeCode
--------+---------------+---------------------+------------
26001087006846 |   Product Name   |         FASAT

1 个答案:

答案 0 :(得分:0)

您应该使用JOIN和相关的on子句来将两个表都加入

    const getUserById = (request, response) => {
      const id = parseInt(request.params.id)

      pool.query('SELECT table_1.GTIN, table_1.gtinNAme, table_2.nutrientTypeCode 
                   FROM table_1 
                   JOIN table_2 ON table_1.GTIN =  table_2.GTIN
                   NWHERE table_1.GTIN = $1', [id], (error, results) => {
        if (error) {
          throw error
        }
        response.status(200).json(results.rows)
      })
    }