一个相当复杂的SQL查询,我可能会变得更加困难: 我有两张桌子:
新闻: newsid,datetime,newstext
照片: pictureid,datetime,imgPath
这两者没有关系,我只是在
上创建新闻/图片的日期加入 到目前为止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)
我必须使用union来模拟MySQL中的完整外连接。 结果:
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
问题在于我显然最终得到了两个日期列 - 一个来自新闻,另一个来自图片,这意味着我无法按日期排序并按正确顺序排列!有任何想法吗?即使这意味着重组数据库!我需要将日期放在一个列中。
答案来自SeRPRo 完成的工作代码是:
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
答案 0 :(得分:3)
只使用你的数据库结构和你的查询,因为在MySQL中没有FULL OUTER JOIN,我认为解决方案可能就是这样:
SELECT
`newsid`,
`text`,
CASE
WHEN `datetime` IS NULL THEN `pdate`
ELSE `datetime`
END as `datetime,
`pcount`
(
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.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.datetime)
)
答案 1 :(得分:0)
我认为你的代码最终会解决这个问题,你能否详细解释日期时间排序部分
SELECT *
FROM News FULL OUTER JOIN Picture
ON News.Datetime = Picture.Datetime ORDER BY DateTime Asc
答案 2 :(得分:0)
您始终可以使用其他查询包装查询:
SELECT ..., IF(datetime1 IS NULL, datetime2, datetime1) as datetime, ... FROM
(
... your query ...
)
ORDER BY datetime