2016-07-26 27 views
2

我有以下MySQL查詢:限制是不是在我的查詢工作

SELECT 
(SELECT count(city) as no_off_total_cityies FROM station) 
- (SELECT count(DISTINCT city) as no_off_total_cityies FROM station) AS sub_value 
FROM station 

工作正常,但是當我在查詢中添加LIMIT 1它不工作

SELECT 
(SELECT count(city) as no_off_total_cityies FROM station) 
- (SELECT count(DISTINCT city) as no_off_total_cityies FROM station) AS sub_value 
FROM station LIMIT 1 
+1

你能附上你得到的錯誤嗎? –

+1

這是不正確的,「限制1」只取得第一個結果。 –

+0

你不能嘗試這個查詢: - SELECT(count(1) - count(DISTINCT city))sub_value from station –

回答

2

嘗試使用OFFSET以及

FROM station LIMIT 1 OFFSET 0 

此外,它看起來像你試圖找到行數城市與城市的不同沒有總沒有之間,所以你可以改爲嘗試得到的結果爲:

SELECT count(city) - count(DISTINCT city) as no_off_total_cityies FROM station 

在這種情況下你不需要使用LIMIT,因爲其結果將是一個單一值(非常類似於Rakesh在他的回答中發佈的內容。

+0

謝謝,但限制1 OFFSET 0也不能正常工作 – bhuwan

+0

@bhuwan: - 你可以定義'不工作'?它是否給出了一些錯誤? –

6

嘗試此查詢: -

SELECT (count(city) - count(DISTINCT city)) sub_value from station 
+2

良好的洞察力,擺脫不必要的'子查詢'。 – 1000111

+0

@ 1000111爲什麼''你爲'子查詢'使用'代碼格式'? –

+0

評論現在是不可變的。順便問一下,我可以問你同樣的問題嗎? :p(#Nevermind)@JanDvorak – 1000111

1

嘗試這樣的:

SELECT sub_value from 
((SELECT count(city) as no_off_total_cityies FROM station) - (SELECT count(DISTINCT city) as no_off_total_cityies FROM station)) AS sub_value limit 1 

否則: 您可以使用左連接是這樣的:

select count1-count2 AS RESULT from 
(select count(encode) as count1 from tbl_ranking) AS A 
LEFT JOIN 
(select count(EnName) AS count2 from tbl_ranking) as B 

ON A.ID = B.ID LIMIT 1 

希望它幫助。

+0

感謝它的工作。 – bhuwan

1

在這裏你不需要使用在你最後使用子查詢爲同一個表。

我有以下MySQL查詢:

選擇 (SELECT COUNT(市)爲no_off_total_cityies從車站) - (SELECT COUNT(DISTINCT市)爲no_off_total_cityies從車站)AS sub_value 從車站

工作正常,但是當我在查詢中添加LIMIT 1它不工作

SELECT 
(SELECT count(city) as no_off_total_cityies FROM station) 
- (SELECT count(DISTINCT city) as no_off_total_cityies FROM station) AS sub_value; 

試試這個。希望這個幫助。