mysql从分区中检索表中的唯一id

时间:2015-01-17 08:34:19

标签: mysql

在这样的表中

ID | Category | Value
1    Device     Computer
1    Location   1st Floor
2    Device     Phone
2    Type       Voip
2    Location   1st Floor
3    Device     Computer
3    Location   2nd Floor

如何获取where device ='computer'和location ='1st Floor'的ID?查询是以编程方式创建的,可能有许多条件指定语句中的单个ID。

2 个答案:

答案 0 :(得分:1)

您可以使用这样的联接查询来解决您的问题。

select a.ID from MYTABLE a, MYTABLE b where a.ID=b.ID and a.Category='Device'
and a.VALUE='Computer' and b.Category='Location' and b.VALUE='1st Floor';

如果有像这样的catogories,那么你必须像下面那样拆分表。

表:

Category with columns (CATOGORY_ID, CATOGORY)
Value with columns (VALUE_ID, VALUE)
MYTABLE with columns (ID, CATOGORY_ID, VALUE_ID)

然后你应该使用连接查询。

答案 1 :(得分:0)

select Distinct a.id 
from myTable a inner join myTable b
 on a.Id = b.Id
Where a.value = 'Computer' And b.value = '1st Floor' and a.Category = 'Device' and b.Category = 'Location'

Demo here