2012-03-20 102 views
0

的結果不同的數據我有一個非常簡單的查詢是這樣的:選擇基於計數

SELECT users.id, COUNT(others.id) as c 
FROM users JOIN other ON users.id=others.user_id 
GROUP BY users.id 

我想這樣做是''c=0替換c數量。

例如,而不是像

# I have this 
1, 0 
2, 1 

# I want c=0 replaced with '' 
1, '' 
2, 1 

我怎麼能在MySQL做這行?

+0

這是相當容易的,但請記住,第二列需要轉換到(var)字符類型和排序成爲一個問題。 NULL是否可以接受? – 2012-03-20 14:37:37

回答

3

試試這個:

SELECT users.id, IF(COUNT(others.id) = 0, '', COUNT(others.id)) as c 
FROM users JOIN other ON users.id=others.user_id 
GROUP BY users.id 
3

使用CASE or IF

SELECT t.id, CASE t.c = 0 THEN '' ELSE t.c FROM (
    SELECT users.id as id, COUNT(others.id) as c 
    FROM users JOIN other ON users.id=others.user_id 
    GROUP BY users.id 
) as t 
0

你可以試試這個:

SELECT users.id, IF(COUNT(others.id) > 0, COUNT(others.id), "''") as c 
FROM users JOIN other ON users.id=others.user_id 
GROUP BY users.id 

或者有COALESCE,但如果不能與0的結果工作

「‘’」(內2個qoutes 2個單引號)會給你

1「」而不是

1,