我有一张包含四个不同数字字段的行表:人物,碎片,英里和行李。所有这些字段现在每行都为0,因为还没有数据。这些行还有两个名为“County”的重要字段,其值是纽约州的县之一,而“Underwater”则只是1/0(是/否)字段。所以他们看起来像这样...
County Underwater People Debris Miles Bags
Richmond 0 0 0 0 0
Rockland 1 0 0 0 0
Nassau 0 0 0 0 0
Queens 1 0 0 0 0
Niagara 0 0 0 0 0
为了将所有这些组合在一起用于PHP页面,我使用了一个包含大量UNION的长SQL语句,并且基本上将结果分别来自纽约市的县,来自长岛的县和Upstate New约克,然后另外两个水下而不是水下的查询,然后是一个总计。我认为使用一次的长语句比对同一个表的六个单独查询更有效,它会省去一些代码行。我在所有数据为0之前使用的是测试数字,并且工作正常。现在所有数据都是0,结果集是一行全0,然后是一行NULL,没有别的。因为我使用foreach PHP循环解析数据,所以它与我的算法紧密相关。我还注意到,如果我将1行的数据(即使只有1个字段)更改为非零,那么我将在结果集中获得另一行。
任何人都可以解释这种行为和解决方案或者提供替代方案吗?如果需要,我可以更深入。
顺便说一句,这是有问题的陈述。待命墙......
SELECT SUM( people ) AS people, SUM( debris ) AS debris, SUM( miles ) AS miles, SUM( bags ) AS bags
FROM `table`
WHERE county='The Bronx' OR county='Kings' OR county='New York' OR county='Queens' OR county='Richmond'
UNION
SELECT SUM( people ) AS people, SUM( debris ) AS debris, SUM( miles ) AS miles, SUM( bags ) AS bags
FROM `table`
WHERE county='Nassau' OR county='Suffolk'
UNION
SELECT SUM( people ) AS people, SUM( debris ) AS debris, SUM( miles ) AS miles, SUM( bags ) AS bags
FROM `table`
WHERE county='Albany' OR county='Allegany' OR county='Broome' OR county='Cattaraugus' OR county='Cayuga' OR county='Chautauqua' OR county='Chemung' OR county='Chenango' OR county='Clinton' OR county='Columbia' OR county='Cortland' OR county='Delaware' OR county='Dutchess' OR county='Erie' OR county='Essex' OR county='Franklin' OR county='Fulton' OR county='Genesee' OR county='Greene' OR county='Hamilton' OR county='Herkimer' OR county='Jefferson' OR county='Lewis' OR county='Livingston' OR county='Madison' OR county='Monroe' OR county='Montgomery' OR county='Niagara' OR county='Oneida' OR county='Onondaga' OR county='Ontario' OR county='Orange' OR county='Orleans' OR county='Oswego' OR county='Otsego' OR county='Putnam' OR county='Rensselaer' OR county='Rockland' OR county='Saratoga' OR county='Schenectady' OR county='Schoharie' OR county='Schuyler' OR county='Seneca' OR county='Steuben' OR county='StLawrence' OR county='Sullivan' OR county='Tioga' OR county='Tompkins' OR county='Ulster' OR county='Warren' OR county='Washington' OR county='Wayne' OR county='Westchester' OR county='Wyoming' OR county='Yates'
UNION
SELECT SUM( people ) AS people, SUM( debris ) AS debris, SUM( miles ) AS miles, SUM( bags ) AS bags
FROM `table`
WHERE underwater = '0' AND county != ''
UNION
SELECT SUM( people ) AS people, SUM( debris ) AS debris, SUM( miles ) AS miles, SUM( bags ) AS bags
FROM `table`
WHERE underwater = '1' AND county != ''
UNION
SELECT SUM( people ) AS people, SUM( debris ) AS debris, SUM( miles ) AS miles, SUM( bags ) AS bags
FROM `table`
WHERE county != '' AND fname != '' AND lname != ''
答案 0 :(得分:4)
使用UNION ALL
代替UNION
。 UNION
运算符会在两个结果集之间抛出重复的行,就像SELECT DISTINCT
对单个结果集一样。 (或者也选择县名,因为这会导致结果行包含不相同的数据。)
要从查询中消除NULL行(这是由空数据集上的SUM()
等聚合函数的结果),只需执行以下操作:
SELECT * FROM (
your query here
) AS x
WHERE x.people IS NOT NULL
或者,将查询中SUM(x)
的每次出现更改为COALESCE(SUM(x), 0)
。