最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

knex.js - How to update one single row? - Stack Overflow

programmeradmin0浏览0评论

I want to update one single row in database, I tried to put the .limit(1), doesn't seem to work with Postgres.

What would you do in this situation?

list.map(async (i) => {
            await kx(table.products)
                .update({ series: i, machine: i.machine })
                .where({
                    series: '',
                    machine: '',
                    purchaseDate: '',
                })
                .limit(1)
        })

I want to update one single row in database, I tried to put the .limit(1), doesn't seem to work with Postgres.

What would you do in this situation?

list.map(async (i) => {
            await kx(table.products)
                .update({ series: i, machine: i.machine })
                .where({
                    series: '',
                    machine: '',
                    purchaseDate: '',
                })
                .limit(1)
        })
Share Improve this question edited Mar 28 at 4:37 angry kiwi asked Mar 27 at 16:54 angry kiwiangry kiwi 11.5k28 gold badges123 silver badges167 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

In PostgreSQL, the .limit(1) is not valid for an UPDATE query because the SQL standard does not allow limiting the number of rows directly in an UPDATE statement.

Instead of using .limit(1), revise the WHERE clause, ensuring that it matches a single, specific row e.g. using id.

list.map(async (i) => {
  await kx(table.claim)
    .update({ series: i, machine: i.machine })
    .where({
      id: i.id 
    });
});

If there is no unique column and your query can match multiple rows, you can use a subquery with the ctid (a system column specific to PostgreSQL). The ctid is unique to each row in the table and can help to target one specific row.

list.map(async (i) => {
  await kx(table.claim)
    .whereRaw('(series = ? AND machine = ? AND purchaseDate = ?) AND ctid IN (SELECT ctid FROM ?? WHERE series = ? AND machine = ? AND purchaseDate = ? LIMIT 1)', 
      ['', '', '', table.claim, '', '', ''])
    .update({ series: i, machine: i.machine });
});
发布评论

评论列表(0)

  1. 暂无评论