node.js - 使用 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。
解决方案
最简单的方法是连接查询:
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);
推荐阅读
- javascript - 嵌套 Map 函数在 react native 中使用 forceUpdate() 时不会更新状态
- visual-studio-code - VS Code devcontainers - remoteUser 和 containerUser 有什么区别?
- hive - 我想从分区表中找出人口第二多的国家
- wordpress - 将帖子类型从创建的自定义帖子类型设置为帖子和页面网格,Genesis Blocks wordpress
- javascript - 使用 vue-mention 获取 this.$scopedSlots.default 不是函数错误
- java - 错误:java.io.IOException:android 11 中没有这样的文件或目录
- django - Django获取百分比过滤对象
- mysql - SQL - 如何从一个表中查询另一个表的条件
- sparql - SELECT FROM DEFAULT 实际上是做什么的?
- cmake - windows下cmake安装libTorch-cpu运行报错问题