Knex.js用于查询作为一个查询

问题描述 投票:0回答:1

这可以作为一个查询完成,因此循环数据库没有多个请求吗?我试图让每个相机最后一张照片,如果有的话。

  async function asyncForEach(array, callback) {
    for (let index = 0; index < array.length; index++) {
      await callback(array[index], index, array);
    }
  }

 let cameras = await knex({ cameras: "device_manager_camera" })
    .select()
    .where("owner_id", 13);

  const start = async () => {
    let report = [];
    asyncForEach(cameras, async camera => {
      let photo = await knex({ photos: "device_manager_photo" })
        .where("camera_id", camera.id)
        .first();
      if (photo) {
        report[camera.name] = photo.timestamp;
      } else {
        report[camera.name] = "never";
      }
    });
    console.log(report);
  };

  start();
javascript knex.js
1个回答
0
投票

首先,我建议您在纯SQL中编写SQL查询,将它转换为knex命令要容易得多。

至于你的请求,我想出了这个返回[{ camera_id, timestamp }]数组的查询。它选择ID为13的所有者的摄像机,并将其连接到表photos的最大时间戳分组查询。

select
  c.name,
  coalesce(t.timestamp::text, 'never') as timestamp
from
  cameras as c
left join (
  select
    p.camera_id,
    max(p.timestamp) as timestamp
  from
    photos as p
  group by
    camera_id
) as t on t.camera_id = c.id
where
  c.owner_id = 13;

如有必要,请更正表名和列。

奖金风格点。我不建议使用timestamp作为列名。它是某些数据库中的保留列,它可能需要在它周围引用它以明确地将其指定为查询中的列,这可能很烦人。

© www.soinside.com 2019 - 2024. All rights reserved.