簡體   English   中英

查詢有關SQL查詢的形成

[英]Query regarding formation of SQL query

我有一個巨大的表格,其中包含以下表格的數據:

Id Col1  Col2      Col3
------------------------
a Fruit1 vitaminA vitaminB 
b a      price       "30"     

現在我想在SQL中檢索所有含有維生素A和維生素B的水果,其價格低於30。 這里'a'是給Fruit1的id。 Fruit1含有維生素A和維生素B. 現在,下一行表示id'a'的價格為30。

我的目的是檢索所有含有維生素A和維生素B且價格低於30的水果。在SQL中我有什么方法可以回答這個問題嗎?

你需要為此加入一個:

select t.col1
from t join
     t tprice
     on t.id = tprice.col1 and
        tprice.col2 = 'price'
where ((t.col2 = 'VitaminA' and t.col3 = 'VitaminB') or
       (t.col2 = 'VitaminB' and t.col3 = 'VitaminA')
      ) and
      (cast(tprice.col3 as int) <= 30)

這是一個非常神秘的數據結構。 你能解釋它的來源嗎?

您必須在表上使用自聯接才能獲得結果。

select t1.id
from yourtable t1
inner join yourtable t2
  on t1.id = t2.col1
where 
(
  t1.col2 = 'vitaminA' and t1.col3 = 'vitaminB'
  or t1.col2 = 'vitaminB' and t1.col3 = 'vitaminA'
)
  and t2.col2 = 'price'
  and cast(t2.col3 as int) < '30';

請參閱SQL Fiddle with Demo

或者您可以使用EXISTS使用WHERE子句:

select t1.id
from yourtable t1
where 
(
  t1.col2 = 'vitaminA' and t1.col3 = 'vitaminB'
  or t1.col2 = 'vitaminB' and t1.col3 = 'vitaminA'
)
  and exists (select t2.col1
              from yourtable t2
              where t2.col2 = 'price'
                and cast(t2.col3 as int) < 30
                and t1.id = t2.col1)

請參閱SQL Fiddle with Demo

另外,您當前的數據結構很難處理。 如果可能,您可能需要考慮重組表。

暫無
暫無

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

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