1

我有以下(mysql)SQL查询:

select a.id, a.name, count(*) as humans
from humans h1, areas a
where h1.gender = 'Female' and h1.area_id = a.id
group by area_id
having count(*) > (
    select count(*)
    from humans h2
    where h2.gender = 'Male' and h1.area_id = h2.area_id
    group by area_id
    )
    or not exists (
    select *
    from humans h2
    where gender = 'Male' and h1.area_id = h2.area_id
    group by area_id
)

这基本上显示了所有由女性主导的领域。

我将如何将其转换为流畅的语法?

从网站上的示例中,我不确定如何使用具有相关性的子查询。

4

1 回答 1

0

如果您有这么大的查询并且您怀疑将来会更改,我建议使用Slick Plain SQL API,原因有两个:

  • 更容易实现
  • 某种更容易支持 - 更清晰的视图

当然,您会失去编译器的时间安全性,但如果您不打算太频繁地更改查询,这可能不是关键的。

所以结果是:

  Database.forURL("jdbc:h2:mem:humans", driver = "org.h2.Driver") withSession { implicit session =>

    val sql = """
    select a.id, a.name, count(*) as humans
    from humans h1, areas a
    where h1.gender = 'Female' and h1.area_id = a.id
    group by area_id
    having count(*) > (
        select count(*)
        from humans h2
        where h2.gender = 'Male' and h1.area_id = h2.area_id
        group by area_id
        )
        or not exists (
        select *
        from humans h2
        where gender = 'Male' and h1.area_id = h2.area_id
        group by area_id
    )
    """

    val result: (Long, String, Long) = StaticQuery.queryNA[(Long, String, Long)](sql).first()

    //do something with the result
  }
于 2014-05-20T09:10:27.287 回答