在多个查询和子查询中更正连接语法

时间:2016-04-19 17:27:37

标签: mysql sql

我有两个查询最终具有相同的格式。每个月/每年都有一个月,一年和一些相关数据。架构如下所示:

subs    Month   Year
8150    1      2015
11060   1      2016
5       2      2014
6962    2      2015
8736    2      2016

Cans    months  years
2984    1       2015
2724    1       2016
13      2       2014
2563    2       2015
1901    2       2016

第一个查询语法如下所示:

SELECT 
    COUNT(personID) AS subs_per_month,
    MONTH(Date_1) AS month_1,
    YEAR(Date_1) AS year_1
FROM
    (SELECT 
        personID, MIN(date) AS Date_1
    FROM
        orders
    WHERE
        isSubscription = 1
    GROUP BY personID
    ORDER BY Date_1) AS my_sub_q
GROUP BY month_1 , year_1

第二个问题:

SELECT 
    COUNT(ID), MONTH(date) AS months, YEAR(date) AS years
FROM
    orders
WHERE
    status = 4 AND isSubscription = 1
GROUP BY months , years
ORDER BY months, years

最终目标是编写一个简单的连接,以便最终数据集如下所示:

subs    cans months years
8150    2984    1   2015
11060   2724    1   2016
5         13    2   2014
6962    2563    2   2015
8736    1901    2   2016

我对如何正确地做到这一点感到有些不知所措,经过大量的试验和所有错误之后,我想我会寻求帮助。令人困惑的是JOIN所处的位置,以及相对于其余语法的外观。

3 个答案:

答案 0 :(得分:1)

在不考虑简化查询的情况下,您可以将两个查询用作内联视图,并且只需从两个选项中进行选择(为了简单起见,我在Q1和Q2中为您的查询和命名字段添加相同内容。

Select Q1.cnt as Subs, Q2.cnt as Cans, Q1.months, Q1.years
from (SELECT 
    COUNT(personID) AS Cnt,
    MONTH(Date_1) as Months,
    YEAR(Date_1) AS years
    FROM  (SELECT personID, MIN(date) AS Date_1
           FROM orders
           WHERE isSubscription = 1
           GROUP BY personID) AS my_sub_q
    GROUP BY month_1 , year_1) Q1
INNER JOIN (SELECT COUNT(ID) cnt, MONTH(date) AS months, YEAR(date) AS years
            FROM orders
            WHERE status = 4 
              AND isSubscription = 1
            GROUP BY months, years) Q2

  ON Q1.Months = Q2.Months
 and Q1.Years = Q2.years
Order by Q1.years, Q2.months

答案 1 :(得分:0)

临时表方法:

create temporary table first_query
<<your first query here>>;

create temporary table second_query
<<your second query here>>;

select fq.subs, sq.cans, fq.months, fq.years
from first_query fq
join second_query sq using (months, years)

您的表格预览和查询列与第一个查询不匹配,因此我假设这两个表都有列 - 月和年。

一种凌乱的查询方法:

SELECT fq.subs_per_month subs, sq.cans, sq.months, sq.years
FROM
(SELECT 
    COUNT(personID) AS subs_per_month,
    MONTH(Date_1) AS month_1,
    YEAR(Date_1) AS year_1
FROM
    (SELECT 
    personID, MIN(date) AS Date_1
    FROM
    orders
    WHERE
    isSubscription = 1
    GROUP BY personID
    ORDER BY Date_1) AS my_sub_q
GROUP BY month_1 , year_1) fq
JOIN
(SELECT 
    COUNT(ID) cans, MONTH(date) AS months, YEAR(date) AS years   -- I added 'cans'
FROM
    orders
WHERE
    status = 4 AND isSubscription = 1
GROUP BY months , years
ORDER BY months, years) sq
ON fq.month_1 = sq.months AND fq.year_1 = sq.years

答案 2 :(得分:0)

请使用以下查询

select t1.subs as subs,t2.Cans as cans,t1.months,t1.year as years from table1 t1 inner join
table2 t2 on t1.month=t2.months and t1.year=t2.years