SQL / SQlite:根据另一列的值在select语句中添加列

时间:2011-06-22 11:40:25

标签: sql sqlite

我有一个包含word, length, position, count and definition列的表格。 我想选择worddefinition但只保留一些单词的定义(基于positioncountlength的条件其余的定义用空字符串替换它们。

我正在进行以下查询:

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

但我最终在列字中出现了重复的值 如何在没有重复值的情况下获得此信息?

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

SELECT DISTINCT似乎可以解决您的问题。

http://www.w3schools.com/sql/sql_distinct.asp

答案 2 :(得分:0)

你可以使用group by子句....

答案 3 :(得分: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