我有以下查询:
SELECT SUM(count)
FROM (SELECT 'artist' AS table_name, COUNT(*) as count FROM artist
UNION
SELECT 'persons' AS table_name, COUNT(*) as count FROM persons
UNION
SELECT 'track' AS table_name, COUNT(*) as count FROM track)
Run Code Online (Sandbox Code Playgroud)
它按预期工作并返回正确的计数.但是现在当我执行以下查询时,我得到的计数不正确:
SELECT SUM(count)
FROM (SELECT COUNT(*) as count FROM artist
UNION
SELECT COUNT(*) as count FROM persons
UNION
SELECT COUNT(*) as count FROM track)
Run Code Online (Sandbox Code Playgroud)
为什么第一个查询获得正确的计数而第二个查询没有?
Joe*_*lli 11
在UNION消除重复值,所以如果两个数正好是相同的,一个是淘汰,只有一个总结.请尝试使用UNION ALL.
SELECT sum(count) FROM
(SELECT COUNT(*) as count FROM artist
UNION ALL
SELECT COUNT(*) as count FROM persons
UNION ALL
SELECT COUNT(*) as count FROM track)
Run Code Online (Sandbox Code Playgroud)