首页 > 解决方案 > 使用 node.js 从 2 个 postgres 表中查询所有数据

问题描述

我正在使用以下节点代码在 postgres 中名为 data 的模式中查询单个表中的所有数据:

const getperson = (request, response) => {
  db.query('SELECT * FROM data.person', (error, results) => {
    if (error) {
      throw error
    }
    response.status(200).json(results.rows)
  })

app.get('/person', getperson)

此模式还包含其他表,我还想从这些表中获取数据,当有人登陆 /getall 时将它们放在一起并显示。

我尝试将查询更改为 this SELECT * FROM data.person JOIN data.animal,但它没有返回任何内容。

或者 this SELECT * FROM data.person, data.animal,但是 this 只返回表中不常见对象的结果,例如,如果 data.person 的 id 为 1 且 data.animal 为 1,它只会返回两者之一的 id。

标签: node.jspostgresql

解决方案


最简单的方法是连接查询:

const getAll = (request, response) => {
  db.query('SELECT * FROM data.person;SELECT * FROM data.animal', (error, data) => {
    if (error) {
      throw error;
    }
    response.status(200).json({people: data[0].rows, animals: data[1].rows});
  })

app.get('/all', getAll);

推荐阅读