quill-插入select语法?

oxf4rvwz  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(373)

因此,由于异步支持,我最近在scala项目中从scalikejdbc转到了quill。
是否支持下面的示例中的任何sql语法?

INSERT INTO People (id, cityID)
SELECT 52, Cities.id
FROM Cities
WHERE Cities.name = 'New York City';

INSERT INTO State (id, numCities)
SELECT 4, COUNT(*)
FROM  Cities
WHERE Cities.state = 'NY'

预期行为

我会尝试这样的事情

quote {
   for {
      count <- query[City].filter(_.state == 'NY').size
   } yield query[State].insert(lift(State(4, count))
}

quote {
   query[City].filter(_.state == 'NY').size.nested.insert(count => lift(State(4, count))
}

但会出现如下错误:
值Map不是long“about”.size的成员
嵌套不是long“about”.size的成员
当然,如果我像下面这样做,我会得到一堆错误:

quote {
   for {
      count <- List(query[City].filter(_.state == 'NY').size)
   } yield query[State].insert(lift(State(4, count))
}

变通办法

目前唯一的解决方法似乎是运行两个独立的查询(一个用于获取计数,另一个用于插入)。但是,如果我做了大量基于select的插入,我会认为这会变得效率低下。

使用原始查询

我尝试过使用中缀的替代方法,例如:

quote {
    infix"""
      INSERT INTO Languages (id,iso639_1,name)
      VALUES (
        (SELECT x2.id + 1
        FROM (SELECT id FROM Languages UNION SELECT 0) x2
        LEFT JOIN Languages x1 ON (x2.id + 1) = x1.id
        WHERE x1.id IS NULL LIMIT 1),
        'Hello',
        'World'
      );
    """.as[?]
}

但它不断地给出这些错误:

[error] (run-main-4a) com.github.mauricio.async.db.mysql.exceptions.MySQLException: Error 1064 - #42000 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO Languages (id,iso639_1,name)
[error]       VALUES (
[error]         (SELECT x2.id ' at line 2
[error] com.github.mauricio.async.db.mysql.exceptions.MySQLException: Error 1064 - #42000 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO Languages (id,iso639_1,name)
[error]       VALUES (
[error]         (SELECT x2.id ' at line 2

这是不正确的,因为我复制粘贴到一个sql浏览器的原始sql,它工作得非常好。

omqzjyyz

omqzjyyz1#

final case class TestTable(id: Long, name: String)

  final val ctx = new SqlMirrorContext(MirrorSqlDialect, Literal)

  import ctx._

  final val table  = quote(query[TestTable])
  final val size   = quote(table.filter(_.name == "hello world").size)
  //the insert action
  final val insert = quote {
    (e: TestTable) => table.insert(e)
  }

//试验

//INSERT INTO TestTable (id,name) VALUES ((SELECT COUNT(*) FROM TestTable x1 WHERE x1.name = 'hello world'), '')
ctx.run(insert(TestTable(size, "")))

相关问题