在一个MySQL中合并2个查询

时间:2018-06-26 08:08:33

标签: mysql sql

第一个SQL查询:

SELECT COUNT(*) FROM (
    SELECT
        rec_business.personal_id,
        rec_business.id AS id,
        rec_personal.l_name AS last_name,
        rec_personal.f_name AS first_name,
        rec_personal.m_name AS middle_name,
        rec_business.bus_name AS bus_name,
        rec_business.reg_type AS reg_type,
        rec_business_type.name AS buss_type,
        rec_business.address AS address,
        rec_business.reg_date AS reg_date,
        rec_business.expire_date AS exp_date
    FROM
        rec_business
        INNER JOIN rec_personal ON rec_business.personal_id = rec_personal.id 
        INNER JOIN rec_business_type ON rec_business_type.id = rec_business.bus_nature
    WHERE rec_business.expire_date > NOW()
) t

第二条SQL查询:

SELECT COUNT(*) FROM (
    SELECT
        rec_business.personal_id,
        rec_business.id AS id,
        rec_personal.l_name AS last_name,
        rec_personal.f_name AS first_name,
        rec_personal.m_name AS middle_name,
        rec_business.bus_name AS bus_name,
        rec_business.reg_type AS reg_type,
        rec_business_type.name AS buss_type,
        rec_business.address AS address,
        rec_business.reg_date AS reg_date,
        rec_business.expire_date AS exp_date
    FROM
        rec_business
        INNER JOIN rec_personal ON rec_business.personal_id = rec_personal.id
        INNER JOIN rec_business_type ON rec_business_type.id = rec_business.bus_nature
    WHERE rec_business.expire_date <= NOW()
) t

如何将这两个查询合而为一

2 个答案:

答案 0 :(得分:3)

这未经测试,但类似....

SELECT 
COUNT(CASE WHEN rec_business.expire_date > NOW() THEN 1 END) AS NotExpired,
COUNT(CASE WHEN rec_business.expire_date <= NOW() THEN 1 END) AS Expired,
COUNT(1) As TotalCount
FROM rec_business
    INNER JOIN rec_personal
        ON rec_business.personal_id = rec_personal.id
    INNER JOIN rec_business_type
        ON rec_business_type.id = rec_business.bus_nature

答案 1 :(得分:0)

sum()是您想要的功能,而不是count()

SELECT SUM(CASE WHEN rcb.expire_date > NOW() THEN 1 ELSE 0 END) AS NotExpired,
       SUM(CASE WHEN rcb.expire_date <= NOW() THEN 1 END) AS Expired,
       COUNT(1) As TotalCount
FROM rec_business rcb INNER JOIN 
     rec_personal rcp
     ON rcb.personal_id = rcp.id INNER JOIN 
     rec_business_type rbt
     ON rbt.id = rcb.bus_nature;