2

以下是我的两个查询,其中仅添加一个左连接结果就会搞砸。第二个查询结果是准确的,但在第一个查询中通过添加一个左连接输出不正确(如您所见,我只添加了一个左连接,但我没有在 where 子句中对该连接进行任何过滤)。请让我知道我该如何解决这个问题?谢谢,

第一个查询:

SELECT Distinct  count(event_id) as event_count from events 
Left Join events on events.event_id = my_events.i_event_id 
Left Join atdees on events.event_id = atdees.fk_event_id

where my_events.v_title != "NULL" and  r_present = 1 and resident_id = '208'  and event_atd > date_sub(curdate(), interval 37 day) group by event_count  order by event_count desc limit 5

结果:

26  |  12   |  11   |   10

第二个查询:

SELECT Distinct  count(event_id) as event_count from events 
Left Join events on events.event_id = my_events.i_event_id 

where my_events.v_title != "NULL" and  r_present = 1 and resident_id = '208'  and event_atd > date_sub(curdate(), interval 37 day) group by event_count  order by event_count desc limit 5

结果:

2  |  1   |  1   |   1
4

2 回答 2

2

左连接的作用是添加额外的(重复的)行。

如果你去掉count并只列出行,你会看到很多重复的行。
这是因为您要的是 and 之间的叉eventsatdees;当然,还有更多的事件和 atdees 组合,而不仅仅是事件。

基本逻辑真的。

将您的顶级查询更改为

SELECT count(distinct event_id) as event_count from events 
Left Join events on events.event_id = my_events.i_event_id 
Left Join atdees on events.event_id = atdees.fk_event_id

where my_events.v_title != "NULL" and  r_present = 1 and resident_id = '208'
and event_atd > date_sub(curdate(), interval 37 day) 
group by event_count  
order by event_count desc 
limit 5

你应该得到相同的结果(虽然这要慢得多)

进一步注意left joins不过滤,它们添加东西。
如果你想过滤你会使用inner joins
这是一个严重的过度简化

Aboutdistinct
关键字可以在聚合函数 的distinct内部和外部起作用。如果你在里面使用它,它只会计算(总和等)唯一值。如果您在聚合函数之外使用它,它只会列出唯一的行。

也就是说:distinct它自己消除了重复的行(它适用于结果集中的所有列)。

distinctin a function 仅用作该函数的过滤器。

于 2012-12-19T15:13:52.077 回答
1

使用COUNT(DISTINCT),而不是DISTINCT COUNT()

SELECT count(distinct event_id) as event_count from events 

COUNT(DISTINCT)将计算不同值的数量,而不是行数......当您添加额外的 时LEFT JOIN,您正在增加行数,从而更改COUNT().

此外,您可能会仔细检查您的GROUP BY... 按聚合函数分组是没有意义的。

于 2012-12-19T15:13:22.947 回答