绘图笔-插入到SELECT ...语法中?

时间:2018-11-03 06:13:15

标签: mysql scala quill

因此,由于异步支持,我最近在我的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))
}

但是它会给出如下错误:

  • 关于“ .size”的“值映射不是Long的成员”
  • 关于“ .size”的“嵌套的不是Long的成员”

当然,如果我做下面的事情,我会得到很多错误:

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

解决方法

当前唯一的解决方法似乎是在运行两个单独的查询(一个用于获取计数,第二个用于插入)。但是我认为如果我做很多基于选择的插入操作,这将变得效率低下。

使用原始查询

我尝试使用infix等替代方法:

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浏览器中,并且运行良好。

1 个答案:

答案 0 :(得分:0)

  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, "")))