有没有办法让以下工作?
SELECT
(SELECT COUNT(foo) FROM table2 WHERE table1.id = table2.id) AS foos
CASE
WHEN foos <= 0 THEN 0
WHEN foos > 0 THEN 1
END
AS isFoos
FROM table1
我得到它的唯一方法是:
SELECT
(SELECT COUNT(foo) FROM table2 WHERE table1.id = table2.id) AS foos
CASE
WHEN (SELECT COUNT(foo) FROM table2 WHERE table1.id = table2.id) <= 0 THEN 0
WHEN (SELECT COUNT(foo) FROM table2 WHERE table1.id = table2.id) > 0 THEN 1
END
AS isFoos
FROM table1
它看起来非常可怕。
请注意,该示例并未描述我有问题的SQL查询,它描述了我想要从查询中获取的语法。
谢谢:)
编辑:修正了SQL以更好地解释问题。
编辑2:这是小提琴,我希望它有所帮助。
http://sqlfiddle.com/#!2/18a45d/2
小提琴包含产品和产品线。产品可以多条生产线,生产线可以生产多种产品。
pr_connected显示应该使用该产品的行数,SELECT计数显示实际使用该产品的行数。
我使用的数据库有一些缺陷,由于写入的代码量不能修复它们。
答案 0 :(得分:1)
SELECT IF(COUNT('foo') > 0, 1, 0) as `isFoos` FROM `table1`
OR
SELECT
`t`.`foos`,
IF(`t`.`foos` > 0, 1, 0) as `isFoos`
FROM
(SELECT COUNT(`x`) AS `foos` FROM `stackoverflow`) as `t`
答案 1 :(得分:1)
我将根据您的更新和sqlfiddle
使用新查询。我将使用子查询,但只有一个COUNT(*)
聚合函数,它将与您的结果相同。
SELECT pr_id, pr_name, connected,
CASE
WHEN connected <= 0 THEN "RED"
WHEN connected < pr_connected THEN "YELLOW"
WHEN connected >= pr_connected THEN "GREEN"
END as Status
FROM (
SELECT pr_id, pr_name, pr_connected,
( SELECT COUNT(pl_id) FROM product_line WHERE pl_product_id = pr_id) AS connected
FROM product
GROUP BY pr_name
) tt
检查我的 Fiddle Demo
答案 2 :(得分:0)
希望这会有所帮助:
select email,
case
when count(email) > 2 then 55
when count(email) < 2 then 33
end
as cc
from supportContacts
group by email
我在这里提出了一个SQL小提琴http://sqlfiddle.com/#!2/94e3dd/10