2013-03-27 77 views
0

的查询我有如下形式的一个巨大的含表中的数据:关于形成SQL查询

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

现在我想找回含维生素A和维生素B有价格低于30 SQL所有的水果。这里'a'是给Fruit1的id。 Fruit1含有维生素A和维生素B.现在,下一行表明id'a'的价格为30.

我的意图是检索所有含维生素A和维生素B且价格低于30的水果。有没有一种方法可以用SQL来回答这个问题?

+6

多么可怕的“模式”。你能再给我几行,这样我们就可以理解如何区分表示该属性的“属性”行中的实体“标题”行以及是否有其他属性被忽略等。 – 2013-03-27 23:03:45

+0

哇。 SQL表格是*不*电子表格。特别是,它们没有固有的顺序,所以标题完全没有意义。这真是非常糟糕的设计,会给你带来很多麻烦和挫折感。 – 2013-03-28 01:08:01

回答

1

你需要做一个加入这个:

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) 

这是一个非常神秘的数据结构。你能解释它来自哪里吗?

+0

@ user1778824。 。 。这是标准的SQL语法,基本上可以在任何数据库中工作。 – 2013-03-27 23:38:53

+0

@ user1778824。 。 。那么,在这种情况下,你无法将它与“30”进行比较。不过,你可以将它与其他东西进行比较。 – 2013-03-27 23:57:06

1

您将不得不在表上使用自联接来获得结果。

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

作为一个侧面说明,当前的数据结构,是工作非常困难用。如果可能的话,你可能想考虑重组你的表格。

+0

@ user1778824该查询应适用于所有现代数据库。 – Taryn 2013-03-27 23:37:36

+0

@ user1778824如果您是比较日期的数据,它会工作。 30不是日期值,因此您无法将其与日期进行比较。 – Taryn 2013-03-28 00:05:20