[英]SQL/SQlite: Adding a column in a select statement based on a value of another column
I have a table with the columns word, length, position, count and definition
. 我有一张桌子,桌子上有word, length, position, count and definition
。 I want to make a select of word
and definition
but just keeping the definition of some words (based on a condition over position
, count
and length
) and the rest of definitions replace them by an empty string. 我想选择word
和definition
但只保留某些单词的定义(基于对position
, count
和length
的条件),其余定义用空字符串替换。
I'm doing the following query: 我正在执行以下查询:
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
But I end up with duplicated values in the column word. 但是我最终在列字中得到重复的值。
How can I get this without duplicated values? 如何获得没有重复值的商品?
Add the inverse WHERE clause to your second set? 在第二个集合中添加反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
A SELECT DISTINCT
seems to solve your problem. SELECT DISTINCT
似乎可以解决您的问题。
http://www.w3schools.com/sql/sql_distinct.asp http://www.w3schools.com/sql/sql_distinct.asp
您可以使用group by子句。
Use of UNION SELECT seems to be useless in your case. 在您的情况下,使用UNION SELECT似乎毫无用处。 It seems that you want only to initialize definition column when it is NULL
. 似乎您只想在NULL
时初始化定义列。 Definition is only part of your outputs. 定义只是您输出的一部分。
Use a ifnull
to initialize definition : 使用ifnull
初始化定义:
SELECT word, IFNULL(definition,"") FROM words
WHERE position = 5000 AND count < 5 AND length <= 6
ORDER BY position ASC, count DESC
IFNULL will return definition is definition is not NULL and "" otherwise. IFNULL将返回定义,定义不为NULL,否则为“”。
SQLITE ISNULL Documentation http://www.sqlite.org/lang_corefunc.html SQLITE ISNULL文档http://www.sqlite.org/lang_corefunc.html
MYSQL IsNULL Documentation: http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_ifnull MYSQL IsNULL文档: http ://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_ifnull
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.