你能否将2个完全不同的查询结果分成1个结果

时间:2013-09-30 20:36:10

标签: mysql sql inner-join division

我试图将两个非常不同的查询中的数值结果分开。

最终结果应为查询1 DIVIDED BY Query 2

查询1 =

SELECT COUNT(DISTINCT(table1.ID)) AS count_1
FROM table1 
    INNER JOIN op 
    INNER JOIN Org 
    ON table1.EID = op.id 
        AND Op.OrgID = Org.ID
WHERE table1.TitleID = 123
    AND op.BrandID = 1 
    AND op.Start <= NOW() AND op.End >= NOW();

查询2 =

SELECT COUNT(DISTINCT user.id) AS count_2
FROM table1 INNER JOIN user INNER JOIN ur
    ON table1.EID = user.id AND ur.userID = user.id
WHERE 
    user.BrandID = 1 
    AND table1.TitleID = 123
    AND ur.role = 0
    AND user.Inactive = 0;

3 个答案:

答案 0 :(得分:4)

当然!你可以使用子选择来实现这一点,虽然它会非常冗长!

SELECT
(
    SELECT COUNT(DISTINCT(table1.ID)) AS count_1
    FROM table1 
        INNER JOIN op 
        INNER JOIN Org 
        ON table1.EID = op.id 
            AND Op.OrgID = Org.ID
    WHERE table1.TitleID = 123
        AND op.BrandID = 1 
        AND op.Start <= NOW() AND op.End >= NOW()
) / (
    SELECT COUNT(DISTINCT user.id) AS count_2
    FROM table1 INNER JOIN user INNER JOIN ur
        ON table1.EID = user.id AND ur.userID = user.id
    WHERE 
        user.BrandID = 1 
        AND table1.TitleID = 123
        AND ur.role = 0
        AND user.Inactive = 0
);

然而格式对你来说感觉最难看。

答案 1 :(得分:2)

使用这样的子查询:

SELECT Q1.count_1 / Q2.Count_2 
FROM 
( ... Query1 ...) AS Q1
JOIN
( ... Query2 ...) AS Q2
ON 1=1

将Query1和Query2替换为您的代码。

答案 2 :(得分:1)

像这样:

SELECT count_1 / count_2
FROM (SELECT COUNT(*) count_1 FROM foo) f
JOIN  (SELECT COUNT(*) count_2 FROM bar) b ON 1=1;

http://sqlfiddle.com/#!2/c215e/1