开发者

MySQL: combining 2 queries (one empty) using UNION ALL results in error "1048 - Column cannot be NULL"

开发者 https://www.devze.com 2023-02-09 04:55 出处:网络
I need to return two different results in a single query. When I run them independently, the first returns no rows (that\'s fine) and the second returns some rows (also fine). When I UNION ALL them, I

I need to return two different results in a single query. When I run them independently, the first returns no rows (that's fine) and the second returns some rows (also fine). When I UNION ALL them, I get 1048 - Column "Date" cannot be null.

I need resulting rows of Date, PW, errors which I will feed a graph to show me what's going on in the system at the points in time specified by Date. In both tables, Date is of the format DateTime and must never be NULL.

SELECT `Date`, COUNT(`ID`) AS `PW`, 0 AS `errors`
FROM `systemlogins`
WHERE `Result` = 'PasswordFailure' AND `Date` >= DATE_SUB(NOW(), INTERVAL 1 DAY)

UNION ALL

SELECT `Date`,  0 AS `PW`, COUNT(`ID`) AS `errors`
FROM `systemerrors`
WHERE `开发者_StackOverflow中文版Date` >= DATE_SUB(NOW(), INTERVAL 1 DAY)

GROUP BY ( 4 * HOUR( `Date` ) + FLOOR( MINUTE( `Date` )/15)) --i.e. full 1/4s of hour
ORDER BY ( 4 * HOUR( `Date` ) + FLOOR( MINUTE( `Date` )/15))

I have read that MySQL might ignore tables' NOT NULL conditions in UNIONs, causing that error. I have indeed removed the "NOT NULL" restriction on the tables and, tada, it works. Now, those restrictions have been put there for a reason and I would like to keep them while running the aforementioned query - is there any way?

Edit: Order is the villain - removing it returns a correct result, albeit with one empty row where Date is NULL. For my purposes, I need to order the results by Date somehow.


Why are you selecting the Date column? Since you are using a aggregate function COUNT, but there is no GROUP BY clause in any of the selects, seems to me that you do not care about the Date column.

Try adding a GROUP BY clause, or removing the Date column from the select.

0

精彩评论

暂无评论...
验证码 换一张
取 消