简体   繁体   中英

Outer Join One table with result of Select Query

I want to add dummy timestamps for distinct days in a table from timestamps that are already present in the table.

I know that I can use outer Join to accomplish this but I haven't succeded so far. Still confused on how to do this. This is what I came up with so far

     SELECT time_stamp from tbl   
 OUTER JOIN y
 SELECT y.time_stamp =
       SELECT DISTINCT DATE_FORMAT(time_stamp, '%Y-%m-%d') FROM tbl ORDER BY DATE(time_stamp) ASC

The original table will look something like this

timestamp           phase_1 phase_2 phase_3
2014-03-04 12:00:00   0       0        0
2014-03-05 02:00:00   0       0        0
2014=03-06 01:00:00   0       0        0
2014-03-07 00:00:00   0       0        0

The result from the query should be something like this

timestamp           phase_1 phase_2 phase_3
2014-03-04 00:00:00   0       0        0
2014-03-04 12:00:00   0       0        0
2014-03-05 00:00:00   0       0        0
2014-03-05 02:00:00   0       0        0
2014=03-06 00:00:00   0       0        0
2014=03-06 01:00:00   0       0        0
2014-03-07 00:00:00   0       0        0

I know that it can be done using the OUTER JOIN query but I can't figure out how. Maybe there is a better way of doing this too.

 SELECT time_stamp from tbl   
 OUTER JOIN y
 SELECT y.time_stamp in(
       SELECT DISTINCT DATE_FORMAT(time_stamp, '%Y-%m-%d') FROM tbl ORDER BY DATE(time_stamp) ASC )

one of the best way using 'IN'

You are looking for a way to include each DATE (at 00:00:00) unless that date (at 00:00:00) already exists.

select
        `timestamp`
      , phase_1
      , phase_2
      , phase_3
from table1

union

select
        date(`timestamp`)
      , phase_1
      , phase_2
      , phase_3
from table1

order by 
        `timestamp`

It is "truncating" each timestamp to a date, then by using UNION all duplicates are removed.

so, From this:

timestamp           phase_1 phase_2 phase_3
2014-03-04 12:00:00   0       0        0
2014-03-05 02:00:00   0       0        0
2014=03-06 01:00:00   0       0        0
2014-03-07 00:00:00   0       0        0

It will produce this

timestamp           phase_1 phase_2 phase_3
2014-03-04 00:00:00   0       0        0     --<< new
2014-03-04 12:00:00   0       0        0
2014-03-05 00:00:00   0       0        0     --<< new
2014-03-05 02:00:00   0       0        0
2014-03-06 00:00:00   0       0        0     --<< new
2014-03-06 01:00:00   0       0        0
2014-03-07 00:00:00   0       0        0

see: http://sqlfiddle.com/#!9/c743a4/2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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