简体   繁体   English

SQL-使用JOINED表进行SELECT

[英]SQL - SELECT with JOINED Table

I'm trying to do a selection from the user tabel. 我正在尝试从用户表中进行选择。 For each user i would like to sum the Timediff for all posts in tblregtime for current user for given date parameters. 对于每个用户,我想将给定日期参数的当前用户在tblregtime所有帖子的tblregtime

Problem is that i need to get information even if there is no registration done at the given date for current user. 问题是,即使在给定日期没有为当前用户进行注册,我也需要获取信息。 If no registration i need output that current user has TotalDiff=0 . 如果没有注册,我需要输出当前用户的TotalDiff=0 My current SQL doesn't work in this way. 我当前的SQL无法以这种方式工作。 It will just give the fname , lname and TotalDiff if there is a post in tblregtime 这将只是给fnamelnameTotalDiff如果在后tblregtime


sql: sql:

 select  u.fname,u.lname, sum(cast(TIME_TO_SEC(TIMEDIFF(r.edate,r.sdate)) AS UNSIGNED)-r.break_time) as TotalDiff

from tbluser u 

RIGHT OUTER JOIN tblregtime r on r.userid=u.id where r.projectid=21
and  year(r.sdate)=2013 and month(r.sdate)=10 and day(r.sdate)=7

If you are trying to keep everything in tbluser , then you want a left join instead of a right join . 如果您试图将所有内容都保留在tbluser ,那么您希望使用left join tbluser而不是right join tbluser However, you also need to move the where conditions into the on clause. 但是,您还需要将where条件移到on子句中。 Otherwise, when there is no match, the comparisons will fail (because the r. values will be NULL ): 否则,当没有匹配项时,比较将失败(因为r.值将为NULL ):

select u.fname,u.lname,
       sum(cast(TIME_TO_SEC(TIMEDIFF(r.edate,r.sdate)) AS UNSIGNED)-r.break_time) as TotalDiff
from tbluser u LEFT JOIN
     tblregtime r
     on r.userid = u.id and
        r.projectid = 21 and
        year(r.sdate) = 2013 and month(r.sdate) = 10 and day(r.sdate) = 7;

I would also recommend that you change the final date comparison to something like: 我还建议您将最终日期比较更改为以下内容:

r.sdate = '2013-10-07'

This form would allow the use of an index on r.sdate . 这种形式将允许在r.sdate上使用索引。 As you have written it, the SQL engine (at least the SQL engines I am familiar with) would not be smart enough to use the index. 如您所写,SQL引擎(至少是我熟悉的SQL引擎)不够聪明,无法使用索引。

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

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