簡體   English   中英

Knex.js作為一個查詢進行查詢

[英]Knex.js for query as one query

可以將其作為一個查詢來完成,這樣就不會有多個請求通過循環傳遞給數據庫嗎? 我試圖讓每個相機的最后一張照片(如果有)。

  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();

首先,建議您使用純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用作列名。 它是某些數據庫中的保留列,可能需要用引號引起來以明確將其指定為查詢中的列,這可能會令人討厭。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM