sql select查询名称 - 值对

时间:2010-10-27 18:05:28

标签: sql

我的表格如下:

ID NAME      VALUE  
 1 home      San Jose  
 1 visitor   New Jersey  
 2 home      Chicago  
 2 visitor   Los Angeles  
 3 home      Tampa Bay   
 3 visitor   Pittsburgh  
 4 home      Montreal  
 4 visitor   N.Y. Islanders  
 5 home      Montreal  
 5 visitor   N.Y. Islanders  
 6 home      Carolina  
 6 visitor   Montreal  
 7 home      Montreal  
 7 visitor   Atlanta    

我如何提出一个SQL查询,该查询将选择具有home = Montreal或visitor = Montreal但不包含其他ID的所有ID。所以在这种情况下,我们将回到4,5,6,7

4 个答案:

答案 0 :(得分:5)

如果'主场'和'访客'是唯一的选择,在两个运动队之间有比赛的例子中似乎是真的,那么就是:

select ID
    from YourTable
    where Value = 'Montreal'

答案 1 :(得分:3)

SELECT
  ID
FROM Table
WHERE
  (Name = 'home' and Value = 'Montreal')
  OR
  (Name = 'visitor' and Value = 'Montreal')

答案 2 :(得分:3)

假设name列包含的值不仅仅是“home”和“visitor” - 最好明确确保获得所需的记录:

SELECT t.id
  FROM YOUR_TABLE t
 WHERE t.name IN ('home', 'visitor')
   AND t.value = 'Montreal'

...否则,在查询中没有包括过滤的值:

SELECT t.id
  FROM YOUR_TABLE t
 WHERE t.value = 'Montreal'

答案 3 :(得分:0)

Select ID from Table where Name = 'home' and Value = 'Montreal'
UNION ALL
Select ID from Table where Name = 'visitor' and Value = 'Montreal'