我在MySQL数据库中有一个booking
表,我需要获取3个数据。
1)总预订
2)待定预订(is_confirm = 1
)
3)完成预订(is_confirm = 0
)
现在,我正在编写3个单独的查询来获取此信息但是如何使用1个查询来获取它?
当前查询:
$booking = new Admin;
$booking->rowQuery("SELECT count(bid) AS totalBooking FROM booking");
$bookingData = $booking->result->fetch_assoc();
$totalBooking = $bookingData['totalBooking'];
$booking->rowQuery("SELECT bid FROM booking WHERE is_confirm = 1 ");
$completeBooking = $booking->rows;
$booking->rowQuery("SELECT bid FROM booking WHERE is_confirm = 0 ");
$pendingBooking = $booking->rows;
答案 0 :(得分:1)
SELECT count(bid) AS totalBooking FROM booking
UNION
SELECT bid FROM booking
WHERE is_confirm=1
UNION
SELECT bid FROM booking
WHERE is_confirm=0
答案 1 :(得分:1)
你可以使用case sql。试试这个:
SELECT
COUNT(CASE WHEN is_confirm = 1 THEN 1 END) AS confirmCount,
COUNT(CASE WHEN is_confirm = 0 THEN 1 END) AS noconfirmCount,
COUNT(*) AS total
FROM booking;
答案 2 :(得分:0)
聚合函数通常会跳过null
,包括group_concat
。如果您以后不介意explode
结果字符串,可以使用case
表达式来获取ID的总预订和逗号分隔字符串:
SELECT COUNT(bid) AS totalBooking,
GROUP_CONCAT(CASE is_confirm WHEN 1 THEN bid END) AS pendingBookings,
GROUP_CONCAT(CASE is_confirm WHEN 0 THEN bid END) AS completeBookings
FROM booking