2015-09-20 22 views
1

我有以下SQL查詢 - 注意:在口頭上更改不同的查詢:在MySQL聲明+回行與大多數比賽

SELECT a.pid,a.city,a.countryCode,b.zipEnabled,b.english 
FROM geoWorld AS a 
JOIN geoCountry AS b ON a.countryCode=b.countryCode 
WHERE a.city IN ("free","dating","donvale","australia"); 

我得到3點返回。

2場比賽'澳大利亞'和1場'donvale'和'澳大利亞'。

有沒有辦法讓我回到最高的比賽?

我可以用PHP來處理結果,但如果我可以單獨使用SQL來處理結果會很好。

歡呼

+1

'集團通過a.city訂購數(a.city)desc'應該解決這個問題。 –

回答

0

嗯,這是什麼意思?

SELECT w.countryCode, count(*) 
FROM geoWorld w JOIN 
    geoCountry c 
    ON w.countryCode = c.countryCode 
WHERE w.city IN ('free', 'dating', 'donvale', 'australia') 
GROUP BY w.countryCode 
ORDER BY count(*) DESC; 
+0

否...需要返回匹配IN語句中的2個值的行。有3個回報,只有一個匹配2個值...我想返回最匹配的行。 – Adam

+0

@Adam。 。 。單行不能匹配兩個單獨的值。 –

+0

@戈登林諾夫:我認爲最高記錄(第一)是按照亞當的預期結果。 – seahawk

0

使用 「分組依據」:

select a.pid,a.city,a.countryCode, b.zipEnabled,b.english, a.c from ( 
    SELECT a.pid,a.city,a.countryCode, count(*) c 
    FROM geoWorld AS a 
    JOIN geoCountry AS b ON a.countryCode=b.countryCode 
    WHERE a.city IN ("free","dating","donvale","australia") 
    group by a.pid,a.city,a.countryCode 
) AS a JOIN geoCountry AS b ON a.countryCode=b.countryCode 
order by c desc 

SELECT a.pid,a.city,a.countryCode,b.zipEnabled,b.english, 
    (select count(*) from geoCountry c where c.countryCode = a.countryCode) ct 
FROM geoWorld AS a 
JOIN geoCountry AS b ON a.countryCode=b.countryCode 
WHERE 
    a.city IN ("free","dating","donvale","australia") 
order by ct desc 

,或者如果你 「需要返回,在報表匹配2個值的行」 具有使用的語句,例如:

select a.pid,a.city,a.countryCode, b.zipEnabled,b.english, a.c from ( 
    SELECT a.pid,a.city,a.countryCode, count(*) c 
    FROM geoWorld AS a 
    JOIN geoCountry AS b ON a.countryCode=b.countryCode 
    WHERE a.city IN ("free","dating","donvale","australia") 
    group by a.pid,a.city,a.countryCode 
    having c=2 
) AS a JOIN geoCountry AS b ON a.countryCode=b.countryCode 
order by c desc 
1

使用limit得到上面記錄着:

SELECT a.pid,a.city,a.countryCode,b.zipEnabled,b.english 
FROM geoWorld AS a 
JOIN geoCountry AS b ON a.countryCode=b.countryCode 
WHERE a.city IN ("free","dating","donvale","australia") 

Group by a.city Order by count(a.city) desc 
limit 1 ;