【问题标题】:Converting a mysql syntax query into sqlite (3)将mysql语法查询转换成sqlite(三)
【发布时间】:2021-06-06 16:06:05
【问题描述】:

我有以下疑问:

Update articles a
inner join 
(
  select article_id, amount_required, amount_sold from products_articles,sales where 
  sales.product_id = products_articles.product_id and sales.id = '4c6d35bf-994a-4689-a32e-5d8196b24b06'
) b on a.id=b.article_id
set a.amount_in_stock=a.amount_in_stock-(amount_required*amount_sold)

虽然它在 mysql(或 mariadb)中运行良好,但我在 sqlite 中运行它时遇到错误:

near "a": syntax error

sqlite 不支持别名还是它们的使用方式?

我将如何转换这种语法?

【问题讨论】:

  • 这能回答你的问题吗? Update with Join in SQLite
  • 那是一篇很棒的帖子,但使用它我仍然无法起草一个有效的 sql 查询

标签: mysql sqlite syntax


【解决方案1】:

SQLite 不支持 UPDATE 语句中的连接。

从 3.33.0 版本开始支持 UPDATE FROM 语法,因此您可以这样做:

with cte as (
  select article_id, amount_required, amount_sold 
  from products_articles pa inner join sales s 
  on s.product_id = pa.product_id 
  where s.id = '4c6d35bf-994a-4689-a32e-5d8196b24b06'
) 
update articles as a
set amount_in_stock = a.amount_in_stock - (c.amount_required * c.amount_sold)
from cte as c  
where c.article_id = a.id

在以前的版本中,您需要一个相关的子查询:

update articles
set amount_in_stock = amount_in_stock - coalesce(
  (
    select amount_required * amount_sold 
    from products_articles pa inner join sales s 
    on s.product_id = pa.product_id 
    where s.id = '4c6d35bf-994a-4689-a32e-5d8196b24b06'
      and article_id = a.id
 ), 0)

【讨论】:

  • 非常感谢您的两个选项,我使用的是 sqlite 3 (v5)。我在这两个方面都接近 \".\": syntax error" ,但我似乎无法弄清楚在哪里
  • @Yonder 没有 v5 版本。执行SELECT sqlite_version() 获取SQLite 的版本。我编辑了。现在语法正确,请检查:dbfiddle.uk/…
  • @Yonder UPDATE 语句中的相关子查询的性能将比 UPDATE FROM 语法差。因此,如果可以将 SQLite 升级到最新版本。
【解决方案2】:
CREATE tABLE articles (id int, amount_in_stock int)
CREATE tABLE products_articles (product_id INT,article_id int)
CREATE tABLE sales (id int,product_id int,amount_required int, amount_sold int)
update articles as a
set amount_in_stock = amount_in_stock - coalesce(
  (
    select amount_required * amount_sold 
    from products_articles pa inner join sales s 
    on s.product_id = pa.product_id 
    where s.id = '4c6d35bf-994a-4689-a32e-5d8196b24b06'
      and article_id = a.id
 ), 0)

db小提琴here

【讨论】:

  • 哇,你甚至没有改变我的代码格式。
猜你喜欢
  • 1970-01-01
  • 2013-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多