簡體   English   中英

SQL / SQlite:根據另一列的值在選擇語句中添加一列

[英]SQL/SQlite: Adding a column in a select statement based on a value of another column

我有一張桌子,桌子上有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

但是我最終在列字中得到重復的值。
如何獲得沒有重復值的商品?

在第二個集合中添加反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

SELECT DISTINCT似乎可以解決您的問題。

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

您可以使用group by子句。

在您的情況下,使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM