我在Mysql中有一个像这样调用的函数:
DB::raw("count_adults(rooms.id) as adults"),
count_adults是这个:
BEGIN
DECLARE adults INT;
SELECT
count(*) INTO adults
FROM
clients
WHERE
clients.room_id = r_id
and (age >= 18
or age = 0);
RETURN adults;
END
但是我想如果这个查询没有返回结果(0)那么做另一个select或function,如下所示:
SELECT count(*) INTO adults FROM client_room, clients
WHERE client_id = clients.id and client_room.room_id = r_id and (age >18 or age = 0)
我可以创建if条件吗?在PHP代码?还是在查询?像这样:
IF EXISTS (SELECT 1 FROM clients WHERE clients.room_id = r_id)
BEGIN
DECLARE adults INT;
SELECT
count(*) INTO adults
FROM
clients
WHERE
clients.room_id = r_id
and (age >= 18
or age = 0);
RETURN adults;
END
ELSE
BEGIN
DECLARE adults INT;
SELECT count(*) INTO adults
FROM
client_room, clients
WHERE
client_id = clients.id and client_room.room_id = r_id
and (age >18
or age = 0);
END
我试过这个似乎有效:
BEGIN
DECLARE adults INT;
SELECT COUNT(*) INTO adults
FROM clients
WHERE clients.room_id = r_id
and (age >= 18 or age = 0);
RETURN IF( adults>0, adults, (SELECT count(*) FROM client_room, clients
WHERE client_id = clients.id
and client_room.room_id = r_id)
);
END
答案 0 :(得分:0)
您可以在查询中使用Array,例如:
CASE
WHEN function1() > 0
THEN function1()
WHEN function2() > 0
THEN function2()
ELSE
0
END
如果function1()
大于0,则将评估返回的值。如果不是function2()
返回的值大于0,则执行此操作。否则就是0。
可以使用列,子查询(即,如果它返回标量),文字等,而不是function1()
,function2()
等。当然,它可以改变到或多或少的条件。