简体   繁体   English

如何编写以下SQL查询

[英]How to write sql query for the following

table - fu_plan_user (id_plan_user,id_user, id_plan, valid_from, valid_to, ...)
table - fu_user (id_user, name, company....)
table - fu_plan (id_plan, name, duration, ...)

This is the table structure somewhat. 这是表结构。

I want to produce a list of accounts that have a close(valid_to) date which is the end of a month(30th day) and this date should be in the future, like grater than todays date (NOW()). 我想生成一个帐户列表,该帐户的截止日期为一个月(第30天)的结束日期(valid_to),该日期应该是将来的日期,例如比今天的日期(NOW())还要高。 The name of the company should not contain "trial" word. 公司名称中不应包含“ trial”字样。

The result should contain the following fields 结果应包含以下字段

id_user, name (from table fu_plan), company (from table fu_user), valid_to (from table fu_plan_user)

Something like this Raw Query (not correct) 像这样的原始查询(不正确)

SELECT usr.id_user, payplan.name, usr.foretag, planUser.da_valid_to
from fu_plan_user planUser, fu_user usr, fu_plan payplan left join
     fu_user usr
     on planUser.id_user=usr.id_user
 where planUser.da_valid_to > now() and
       planUser.da_valid_to >= DATEADD(d, -30, getdate()) ;

After your explanation and only if your database is MySQL, i suggest to use this query: 经过您的解释并且仅当您的数据库是MySQL时,我建议使用此查询:

SELECT user.id_user, plan.name, user.company, pbyu.valid_to 
FROM fu_plan_user AS fbyu
    JOIN fu_user AS user
        ON user.id_user = fbyu.id_user 
    JOIN fu_plan AS plan
        ON plan.id_plan = fbyu.id_plan
WHERE pbyu.valid_to > NOW()
    AND LAST_DAY(pbyu.valid_to) = pbyu.valid_to
    AND  user.company NOT LIKE '%trial%';

If company isn't only lowercase values, you should use LOWER(). 如果company不仅是小写的值,则应使用LOWER()。 LAST_DAY() function will get the last day from month of valid_to date. LAST_DAY()函数将获取有效日期的月份中的最后一天。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM