我有2个表Publisher和Book。Book在Publisher上有一个外键。我想知道出版商是否有书籍。通过下面的SQL表达式,我可以知道每个出版商有多少本书。但是如何转换{{ 1}}为布尔值?
Count(Book.uuid)
答案 0 :(得分:0)
一个选项使用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;