2012-10-17 71 views
4

我有一个MySQL数据库(item_preset)如下表:多行条件MySQL的不同列

+-----+-----------+---------+-------+ 
| id | preset_id | item_id | value | 
+-----+-----------+---------+-------+ 
| 1 | 1   | 1  | 2  | 
| 2 | 1   | 2  | 1  | 
| 3 | 1   | 4  | 60 | 
| 4 | 1   | 3  | 16 | 
| 5 | 1   | 3  | 17 | 
| 6 | 1   | 3  | 18 | 
| 7 | 1   | 3  | 25 | 
| 8 | 1   | 3  | 26 | 
| 9 | 1   | 3  | 27 | 
| 10 | 2   | 1  | 3  | 
| 11 | 2   | 2  | 0  | 
| 12 | 2   | 4  | 0  | 
| 13 | 2   | 3  | 16 | 
| 14 | 2   | 3  | 17 | 
| 15 | 2   | 3  | 19 | 
| 16 | 2   | 3  | 20 | 
| 17 | 2   | 3  | 21 | 
| 18 | 3   | 1  | 2  | 
| 19 | 3   | 2  | 0  | 
| 20 | 3   | 4  | 0  | 
| 21 | 3   | 3  | 25 | 
| 22 | 3   | 3  | 28 | 
| 23 | 4   | 1  | 1  | 
| 24 | 4   | 2  | 1  | 
| 25 | 4   | 4  | 120 | 
| 26 | 4   | 3  | 16 | 
| 27 | 4   | 3  | 17 |   
| 28 | 4   | 3  | 18 | 
| 29 | 4   | 3  | 22 | 
| 30 | 4   | 3  | 23 | 
| 31 | 4   | 3  | 24 | 
| 32 | 6   | 1  | 3  | 
| 33 | 6   | 2  | 1  | 
| 34 | 6   | 4  | 90 | 
| 35 | 6   | 3  | 18 | 
| 36 | 6   | 3  | 22 | 
| 37 | 6   | 3  | 23 | 
| 38 | 6   | 3  | 24 | 
| 39 | 6   | 3  | 29 | 
| 40 | 6   | 3  | 30 | 
+-----+-----------+---------+-------+ 

我想这样做的就是基于多行条件的不同preset_id。 如获得preset_id 1,我需要的所有条件为真(ITEM_ID = 1和value_id = 2),(ITEM_ID = 2和值= 1),等等

我已经试过usintg如下: (item_id = 1和value = 2)和(item_id = 2和value = 1)和(item_id = 4和value = 60),从item_preset中选择不同的preset_id;

但得到一个空集。如果我尝试使用Or's而不是,并且我获得了与任何条件匹配的所有preset_ids。

任何想法?

感谢

+0

什么是你想要的结果? –

+0

要得到一个preset_id,我将不得不使所有匹配item_id和该预设值的行。 – Bobkatt

+0

例如要得到preset_id 1我将不得不item_id = 1 - 9行的值。很难解释 – Bobkatt

回答

1

你可以尝试这样的事情:

select distinct preset_id from item_preset 
where preset_id in (select preset_id from item_preset where item_id = 1 and value = 2) 
and preset_id in (select preset_id from item_preset where item_id = 2 and value = 1) 
and preset_id in (select preset_id from item_preset where item_id = 4 and value = 60); 
+0

工程处理,谢谢堆 – Bobkatt

+0

是否有可能检查查询中是否包含与preset_id匹配的所有行? – Bobkatt

+0

你的意思是? (从item_preset中选择不同的preset_id 其中preset_id在(从item_preset中选择item_id = 1且值= 2) 和preset_id in(从item_preset中选择item_id = 2且value = 1的preset_id) 和preset_id in(从item_preset中选择preset_id,其中item_id = 4且值= 60));' –

1

多个支架,

select distinct(preset_id) from item_preset where ((item_id = 1 and value = 2) or (item_id = 2 and value = 1) or (item_id = 4 and value = 60)); 

和值是keyword - 不使用值作为column name

2

你可能想试试这个东西,

SELECT preset_id 
FROM tableName 
WHERE (item_id = 1 and value = 2) OR 
     (item_id = 2 and value = 1) OR 
     (item_id = 4 and value = 60) 
GROUP BY preset_id 
HAVING COUNT(*) = 3 

SQLFiddle Demo