【问题标题】:mysql select if datediff is greater thanmysql 选择如果 datediff 大于
【发布时间】:2017-11-28 11:55:42
【问题描述】:

只有当 date_start 和 date_end 的时间差异大于 3 个月时,我才想查询 lat 3 年的用户。我尝试了很多东西,但没有任何效果。这是我到现在为止的声明:

SELECT accounts.account_id, accounts.name, accounts.active_club_id, 
accounts.phone, MIN(shifts_accounts.date_start) as 'datestart', MAX(shifts_accounts.date_end) as 'dateend' 
FROM `shifts_accounts` 
JOIN accounts ON shifts_accounts.account_id = accounts.account_id 
JOIN accounts_groups ON accounts.account_id = accounts_groups.account_id 
WHERE accounts_groups.group_id = 7 
AND DATEDIFF('dateend',  'datestart') > 90 
AND accounts.active_club_id != 1 
AND shifts_accounts.date_start > '2014-11-28' 
AND shifts_accounts.date_start < '2017-11-28' GROUP BY accounts.account_id

【问题讨论】:

  • 您不能以这种方式引用别名。但你可以在这种情况下使用 HAVING。

标签: mysql


【解决方案1】:

以下是有效查询的示例。我认为没有足够的信息来说明它是否是你想要的......

SELECT a.account_id
     , a.name
     , a.active_club_id
     , a.phone
     , MIN(sa.date_start) datestart
     , MAX(sa.date_end) dateend 
  FROM shifts_accounts sa
  JOIN accounts a
    ON a.account_id = sa.account_id 
  JOIN accounts_groups ag
    ON ag.account_id = a.account_id 
 WHERE ag.group_id = 7 
   AND a.active_club_id != 1 
   AND sa.date_start BETWEEN '2014-11-28' AND '2017-11-28' 
 GROUP 
    BY a.account_id
HAVING DATEDIFF(dateend, datestart) > 90;

如需进一步帮助,请参阅:Why should I provide an MCVE for what seems to me to be a very simple SQL query?

【讨论】:

  • 我爱你 :) 非常感谢你并感谢你提供相关链接。
【解决方案2】:

试试这个,

SELECT accounts.account_id, accounts.name, accounts.active_club_id, 
accounts.phone, MIN(shifts_accounts.date_start) as 'datestart', MAX(shifts_accounts.date_end) as 'dateend' 
FROM `shifts_accounts` 
JOIN accounts ON shifts_accounts.account_id = accounts.account_id 
JOIN accounts_groups ON accounts.account_id = accounts_groups.account_id 
WHERE accounts_groups.group_id = 7 
AND DATEDIFF('dateend',  'datestart') > 90 
AND accounts.active_club_id != 1 
AND shifts_accounts.date_start < DATE_SUB(NOW(),INTERVAL 3 YEAR) GROUP BY accounts.account_id

【讨论】:

  • 这有点帮助。谢谢你。这不是我的意思,所以我将编辑我的问题,以确保你能理解。
  • 有或没有引号,WHERE ... dateend 在这里永远不会是一个有效的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-04
相关资源
最近更新 更多