2011-06-22 44 views
0

我有一個表格,其列word, length, position, count and definition。 我想要選擇worddefinition,但只是保留一些單詞的定義(基於條件超過positioncountlength),其餘定義將其替換爲空字符串。SQL/SQlite:根據另一列的值在select語句中添加一列

我做下面的查詢:

SELECT word,definition FROM (SELECT word, definition, position, count FROM words 
WHERE position = 5000 AND count < 5 AND length <= 6 
AND definition IS NOT NULL 
UNION ALL 
SELECT word, "" AS definition, position, count FROM words) 
ORDER BY position ASC, count DESC 

但我最終列字重複值。
我怎樣才能得到這個沒有重複的值?

回答

1

添加逆WHERE子句的第二套?

SELECT word,definition FROM 
(
    SELECT word, definition, position, count FROM words 
    WHERE position = 5000 AND count < 5 AND length <= 6 
    AND definition IS NOT NULL 
UNION ALL 
    SELECT word, "" AS definition, position, count FROM words 
    WHERE NOT (position = 5000 AND count < 5 AND length <= 6 
      AND definition IS NOT NULL) 
) 
ORDER BY position ASC, count DESC 
+0

爲什麼不使用'CASE WHEN(condition)THEN definition ELSE「」END'? – Benoit

0

您可以通過子句中使用組....

0

使用UNION SELECT似乎對您的情況沒用。 看起來你只想初始化定義列,當它是NULL。 定義只是你輸出的一部分。

使用ifnull初始化定義:

SELECT word, IFNULL(definition,"") FROM words 
    WHERE position = 5000 AND count < 5 AND length <= 6 
ORDER BY position ASC, count DESC 

IFNULL將返回定義的定義不爲NULL和 「」,否則。

SQLITE ISNULL文檔 http://www.sqlite.org/lang_corefunc.html

MYSQL ISNULL文檔: http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_ifnull

+1

如果可能的話,你可能更喜歡'COALESCE()'到IFNULL,它可以有可變數量的參數(你應該鏈接到[SQLite文檔](http://sqlite.org/lang_corefunc.html),因爲問題是標記SQLite,而不是MySQL) – Benoit

相關問題