A rather complicated sql query, which I can do is much more complicated than it should be: I have two tables:
News: newsid, datetime, newstext
Photo: pictureid, datetime, imgPath
Both are not related to each other, I join only the date the news / image was created on
SQL:
SELECT * FROM news as n LEFT OUTER JOIN (SELECT count(pictureid), datetime FROM picture GROUP BY DATE(datetime)) as p ON DATE(n.datetime) = DATE(p.datetime) UNION SELECT * FROM news as n RIGHT OUTER JOIN (SELECT count(pictureid), datetime FROM picture GROUP BY DATE(datetime)) as p ON DATE(n.datetime) = DATE(p.datetime)
I need to use union to simulate a full outer join in MySQL. Results:
newsid text datetime count() datetime 1 sometext 2011-01-16 1 2011-01-16 2 moo2 2011-01-19 NULL NULL 3 mooo3 2011-01-19 NULL NULL NULL NULL NULL 4 2011-01-14
The problem is that I obviously get two date columns - one of the news and one of the images, which means that I cannot sort by date and be in the correct order! Any ideas? Even if it means restructuring the database! I need a date to be in one column.
Reply from SeRPRo Completed working code:
SELECT `newsid`, `text`, CASE WHEN `datetime` IS NULL THEN `pdate` ELSE `datetime` END as `datetime`, `pcount` FROM ( (SELECT * FROM news as n LEFT OUTER JOIN (SELECT count(pictureid) as pcount, datetime as pdate FROM picture GROUP BY DATE(datetime)) as p ON DATE(n.datetime) = DATE(p.pdate) ORDER BY datetime ) UNION (SELECT * FROM news as n RIGHT OUTER JOIN (SELECT count(pictureid) as pcount, datetime as pdate FROM picture GROUP BY DATE(datetime)) as p ON DATE(n.datetime) = DATE(p.pdate) ORDER BY datetime ) ) as x ORDER BY datetime
mysql
Charli
source share