Click here to Skip to main content
15,910,981 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello,

i want record from table by date. if any particular date, record is not available then date must come with null data.

eg.
  date--------------id---------name
2015/09/01-----------1---------abc1
2015/09/02-----------2---------abc2
2015/09/04-----------3---------abc3
2015/09/06-----------4---------abc4


and i want something like this.

  date--------------id---------name
2015/09/01-----------1---------abc1
2015/09/02-----------2---------abc2
2015/09/03---------null--------null
2015/09/04-----------3---------abc3
2015/09/05---------null--------null
2015/09/06-----------4---------abc4


Thnaks In Advance..
Posted
Updated 21-Sep-15 21:35pm
v2
Comments
Maciej Los 22-Sep-15 3:36am    
What have you tried?

1 solution

Unfortunately generating sequences in MySQL is not quite as easy as it is in MSSQL.

However, I adapted a solution by logan5 at SO[^]

This is my interpretation of your table:
SQL
CREATE TABLE your_table
(
  datecol DATE,
  id INT,
  namecol VARCHAR(255)
);
INSERT INTO your_table (datecol, id, namecol) VALUES('2015/09/01',1,'abc1');
INSERT INTO your_table (datecol, id, namecol) VALUES('2015/09/02',2,'abc2');
INSERT INTO your_table (datecol, id, namecol) VALUES('2015/09/04',3,'abc3');
INSERT INTO your_table (datecol, id, namecol) VALUES('2015/09/06',4,'abc4');
I created a "working" table
SQL
CREATE TABLE num (i int);
INSERT INTO num (i) VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);

Which I then used in this query:
SQL
select adddate('2015-09-01', numlist.id) as `date` , y.id, y.namecol
from
(SELECT n1.i + n10.i*10 + n100.i*100 AS id
   FROM num n1 cross join num as n10 cross join num as n100) as numlist
LEFT OUTER JOIN your_table y on y.datecol = adddate('2015-09-01', numlist.id)
where adddate('2015-09-01', numlist.id) <= '2015-09-30';

It produces the results you are after.

If you are going to do this often it is probably worth setting up a permanent table of dates
 
Share this answer
 
Comments
Maciej Los 22-Sep-15 15:28pm    
5ed!
CPallini 22-Sep-15 16:23pm    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900