分组后如何将count转换为boolean值

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

我有两个表publisher和book.book在publisher上有一个外键。我想知道publisher是否有图书。通过下面的sql表达式,我可以知道每个publisher有多少图书。但是如何转换 Count(Book.uuid) 一个布尔值?

select publisher.uuid, Count(Book.uuid)
from Publisher
left join Book
    on Publisher.uuid = Book.publisher_id
group by Publisher.uuid
tvokkenx

tvokkenx1#

一个选项使用 CASE 表达式:

SELECT
    p.uuid,
    CASE WHEN COUNT(b.uuid) > 0 THEN 'true' ELSE 'false' END AS has_count
FROM Publisher p
LEFT JOIN Book b
    ON p.uuid = b.publisher_id
GROUP BY p.uuid;

如果您想要一个实际的布尔表达式,那么只需将计数直接与一个值进行比较即可。

SELECT
    p.uuid,
    COUNT(b.uuid) > 0 AS has_count
FROM Publisher p
LEFT JOIN Book b
    ON p.uuid = b.publisher_id
GROUP BY p.uuid;

相关问题