2010-11-03 166 views
1

我有兩個查詢。第一個返回一些結果,第二個返回任何結果。他們來了。應該相當的兩個查詢返回不同的結果

這一個返回一些結果:

select md5(concat(ad.line1, ad.line2, ad.city, s.name, ad.zip, group_concat(distinct c.name))) id, 
     group_concat(distinct c.name) customer_names, 
     count(distinct c.name) number_of_customers, 
     ad.line1, 
     ad.line2, 
     ad.city, 
     s.name state_name, 
     ad.zip, 
     a.import_id 
    from address ad 
    join account_address aa on aa.address_id = ad.id 
    join account a on aa.account_id = a.id 
    join import i on a.import_id = i.id 
    join customer c on a.customer_id = c.id 
    join state s on ad.state_id = s.id 
where a.import_id = 188 
group by s.name, city, zip, line1, line2 

這將返回什麼:

select * from 
(select md5(concat(ad.line1, ad.line2, ad.city, s.name, ad.zip, group_concat(distinct c.name))) id, 
     group_concat(distinct c.name) customer_names, 
     count(distinct c.name) number_of_customers, 
     ad.line1, 
     ad.line2, 
     ad.city, 
     s.name state_name, 
     ad.zip, 
     a.import_id 
    from address ad 
    join account_address aa on aa.address_id = ad.id 
    join account a on aa.account_id = a.id 
    join import i on a.import_id = i.id 
    join customer c on a.customer_id = c.id 
    join state s on ad.state_id = s.id 
group by s.name, city, zip, line1, line2) v 
where v.import_id = 188 

我完全迷惑。有任何想法嗎?

我的DBMS是MySQL。

+0

我建議你'SET sql_mode ='ONLY_FULL_GROUP_BY'',直到你熟悉'GROUP BY'的工作方式。 – Quassnoi 2010-11-03 19:08:14

回答

2

第二個查詢是濫用MySQL擴展名爲GROUP BY,允許選擇未聚合的列。

import_id從第二個查詢中的每個組的隨機記錄中選擇,並且不能保證它將是188。但是查詢在GROUP BY之後檢查它。

的樣本數據:

grouper value 
1   1 
1   1 
1   2 
1   3 
2   1 
2   2 
2   3 

首先查詢:

SELECT grouper, value 
FROM mytable 
WHERE value = 1 

grouper value 
1   1 
1   1 
2   1 

由於WHERE執行GROUP BY之前,這個查詢纔會考慮控股value = 1記錄(這在以前的階段上返回):

SELECT grouper, COUNT(*) 
FROM  mytable 
WHERE value = 1 
GROUP BY 
     grouper 

grouper COUNT(*) 
1   2 
2   1 

第二個q uery:

SELECT grouper, COUNT(*), value 
FROM  mytable 
GROUP BY 
     grouper 

grouper COUNT(*) value 
1   4   2 
2   3   3 

由於value不分組並沒有聚集,它可以從採取組內的任何紀錄!在這種情況下,這是從最後的記錄或適當的組中取得的(但也可以從任何其他記錄中獲取)。

SELECT * 
FROM  (
     SELECT grouper, COUNT(*), value 
     FROM  mytable 
     GROUP BY 
        grouper 
     ) q 
WHERE value = 1 

-- no rows 

由於存在與value = 1沒有記錄前階段(它發生,這樣的數值是從其他記錄拍攝)上,沒有記錄滿足WHERE條件。

相關問題