我有以下(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
)
这基本上显示了所有由女性人主导的领域。
我究竟如何将其转换为光滑的语法?
我不清楚网站上的示例如何使用具有相关性的子查询。
答案 0 :(得分: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
}