如何将单个MySQL表的03 SELECT语句/ MySQL查询组合在一起

时间:2017-04-03 15:54:28

标签: mysql

我希望从单个MySQL表中提取:

  1. 向今天过生日的用户发送电子邮件,并在接下来的06天过生日。
  2. 查询:

    SELECT * 
    FROM  table_01
    WHERE  DATE_ADD(date_of_birth, INTERVAL YEAR(CURDATE())-YEAR(date_of_birth)
           + IF(DAYOFYEAR(CURDATE()) = DAYOFYEAR(date_of_birth),1,0) YEAR) 
        BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 6 DAY);
    
    1. 向仅为01年/ 365天的用户发送电子邮件。
    2. 查询:

      SELECT *, TIMESTAMPDIFF(day, date_of_registration, NOW()) 
       FROM table_01 
       WHERE TIMESTAMPDIFF(day, date_of_registration, NOW()) = 365;
      
      1. 向男性用户发送电子邮件。

        SELECT * FROM table_01 where gender = male;

      2. 我使用了JOIN,UNION命令,但仍无效。

        请建议。

4 个答案:

答案 0 :(得分:1)

SELECT *,
    IF(DATE_ADD(`date_of_birth`, INTERVAL YEAR(CURDATE())-YEAR(`date_of_birth`) + IF(DAYOFYEAR(CURDATE()) = DAYOFYEAR(`date_of_birth`),1,0) YEAR) BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 6 DAY),1,0) as `matchtype1`,
    IF(TIMESTAMPDIFF(day, `date_of_registration`, NOW()) = 365,1,0) as `matchtype2`,
    IF(`gender` = 'male',1,0) as `matchtype3`
FROM `table_01`
WHERE (DATE_ADD(`date_of_birth`, INTERVAL YEAR(CURDATE())-YEAR(`date_of_birth`) + IF(DAYOFYEAR(CURDATE()) = DAYOFYEAR(`date_of_birth`),1,0) YEAR) BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 6 DAY))
    AND (TIMESTAMPDIFF(day,`date_of_registration`, NOW()) <= 365)
    AND (`gender` = 'male')
ORDER BY `date_of_registration`;

答案 1 :(得分:0)

不完全确定我完全明白需要。 (我一直关注直到性别位。)我没有你的架构,所以这是未经测试的。

 SELECT *
  ,FLOOR(DATEDIFF(dd,date_of_birth,GETDATE()) / 365.25) AS AGE_NOW
  ,FLOOR(DATEDIFF(dd,date_of_birth,GETDATE() + 6) / 365.25) AS AGE_SIX_DAYS_FROM_NOW
  ,TIMESTAMPDIFF(day, date_of_registration, NOW()) AS ACCOUNT_AGE
FROM "table_01" EMP
WHERE 1 = (FLOOR(DATEDIFF(dd,EMP.date_of_birth,GETDATE()+7) / 365.25))
          -
          (FLOOR(DATEDIFF(dd,EMP.date_of_birth,GETDATE()) / 365.25))
          OR (ACCOUNT_AGE = 365)
          OR (EMP.gender = 'male');

答案 2 :(得分:0)

UNION没有动摇,因为第二个查询比其他查询更多地返回一列:

SELECT *, TIMESTAMPDIFF(day, date_of_registration, NOW()) 
 FROM table_01 
 WHERE TIMESTAMPDIFF(day, date_of_registration, NOW()) = 365;

因此您需要向其他查询添加列或删除第二列。

并且您在所有查询中使用一个表为什么三个查询只使用一个并使用或

select 
    *, TIMESTAMPDIFF(day, date_of_registration, NOW())
  from table_01 where 
 (condition of the first query)
   or 
 (condition of the second query)
  or 
(condition of the third query)

答案 3 :(得分:-1)

你使用的是两个&#34 ;;&#34;,也许这就是问题所在。

SELECT SUM(...) AS AEROWiz
FROM ...

UNION

SELECT SUM(...) AS AEROWiz
FROM ...

您还可以使用AND | OR

组合第1和第3个sql语句