我有两个数据库表:
subscribers: (ID, name, email_address etc)
和 订阅:(subsc_id,user_id,subsc_start,subsc_end)
我的问题是如何获得所有过期会员的结果?我写了一个SQL查询:
SELECT *
FROM subscriptions
LEFT JOIN subscribers
ON subscriptions.user_id = subscribers.ID
WHERE DATE(subscription.subsc_end) < DATE(NOW())
GROUP BY subscriptions.user_id
问题是,如果订阅者具有有效订阅但也具有较早的过期订阅,则该订阅者也将被添加到过期列表中。
有人可以帮我写出正确的查询吗?
谢谢
答案 0 :(得分:2)
因此,您希望找到过期日期为过去的用户,并且他们的开始日期在到期日之前 - 请尝试以下操作:
SELECT * FROM subscriptions
LEFT JOIN subscribers
ON subscriptions.user_id = subscribers.ID
WHERE DATE(subscriptions.subsc_end) < DATE(NOW())
AND DATE(subscriptions.subsc_start) < DATE(subscriptions.subsc_end)
GROUP BY subscriptions.user_id
HAVING MAX(DATE(subscriptions.subsc_end)) < DATE(NOW())
答案 1 :(得分:1)
您可以尝试使用having子句:
SELECT * FROM subscriptions
LEFT JOIN subscribers
ON subscriptions.user_id = subscribers.ID
GROUP BY subscriptions.user_id
HAVING MAX(DATE(subscriptions.subsc_end)) < DATE(NOW())
答案 2 :(得分:0)
为什么不随时更新他的“软删除”旧订阅? 在第二个表格中添加“续订”字段,只要有人续订订阅,请将时间戳推送到旧版的续订字段,以便在查询中将其排除?
答案 3 :(得分:0)
使用php脚本执行此操作,以便显示所有过期的用户。
$get_exp = mysql_query("SELECT * FROM subscriptions LEFT JOIN subscribers ON subscriptions.user_id = subscribers.ID GROUP BY subscriptions.user_id") or die(mysql_error());;
while($row=mysql_fetch_assoc($get_exp)){
$now = time();
$end_date = strtotime($row['subsc_end']);
$exp_date = ($end_date - $now);
$totDays = floor($datediff/(60*60*24));
if($totDays < 0){
//display user, he/she expired
}
}
答案 4 :(得分:0)
可能最容易对订阅者的非过期订阅进行LEFT OUTER JOIN,并检查WHERE子句中是否找不到未过期的订阅。
保存所有聚合函数。
SELECT *
FROM subscribers
LEFT JOIN subscriptions
ON subscriptions.user_id = subscribers.ID
AND DATE(subscription.subsc_end) > DATE(NOW())
WHERE subscriptions.subsc_id IS NULL