结合多个MySQL选择查询的结果

时间:2015-11-11 03:11:25

标签: mysql select

我是MySQL新手,正在寻找有关组合查询结果的帮助。我有三种不同的SELECT查询,用于根据成员的日期范围选择用户列表:10到25年之间,25到50年之间,以及50年或更长时间。这些查询目前如下:

返回至少10年但少于25岁的成员:

SELECT `user`.id AS "Member #",
`user`.initiation_date AS "Initiation Date"
FROM `user`
WHERE `user`.initiation_date BETWEEN CURDATE() - INTERVAL 25 YEAR AND CURDATE() - INTERVAL 10 YEAR

返回至少25年但少于50岁的成员:

SELECT `user`.id AS "Member #",
`user`.initiation_date AS "Initiation Date"
FROM `user`
WHERE `user`.initiation_date BETWEEN CURDATE() - INTERVAL 50 YEAR AND CURDATE() - INTERVAL 25 YEAR

返回至少50年的成员:

SELECT `user`.id AS "Member #",
`user`.initiation_date AS "Initiation Date"
FROM `user`
WHERE `user`.initiation_date <= CURDATE() - INTERVAL 50 YEAR

这三个似乎独立工作,但我的目标是结合这些查询的结果来返回user.id,user.initiation_date,以及第三列,以确定成员是否在“10”年“(查询1),”25年“(查询2)或”50年“(查询3)范围。

非常感谢任何帮助或指导。

2 个答案:

答案 0 :(得分:0)

这里有两个选择。

选项1(UNION)

SELECT `user`.id AS "Member #",
`user`.initiation_date AS "Initiation Date",
"10 Year" AS myRange
FROM `user`
WHERE `user`.initiation_date BETWEEN CURDATE() - INTERVAL 50 YEAR AND CURDATE() - INTERVAL 25 YEAR

UNION

SELECT `user`.id AS "Member #",
`user`.initiation_date AS "Initiation Date",
"25 Year" AS myRange
FROM `user`
WHERE `user`.initiation_date BETWEEN CURDATE() - INTERVAL 50 YEAR AND CURDATE() - INTERVAL 25 YEAR

选项2(CASE)

您还可以使用WHERE子句选择具有10年或更长成员资格的成员,然后在SELECT语句中使用CASE子句。

答案 1 :(得分:0)

尝试这一点,这将有效。

SELECT `user`.id AS Member_No,
    `user`.initiation_date AS Initiation_Date,
    (CASE WHEN `user`.initiation_date BETWEEN (CURDATE() - INTERVAL 25 YEAR) AND (CURDATE() - INTERVAL 10 YEAR) THEN '10 Year' 
          WHEN `user`.initiation_date BETWEEN (CURDATE() - INTERVAL 50 YEAR) AND (CURDATE() - INTERVAL 25 YEAR) THEN '25 Year'
          WHEN `user`.initiation_date <= (CURDATE() - INTERVAL 50 YEAR) THEN '50 Year'
          ELSE 'None'
           END) AS Year_category
    FROM `user`

希望这有帮助