sql检查连接表是否包含mutliple标准的行

时间:2016-01-23 14:07:44

标签: sql postgresql

我有两个表,资产和asset_params。

资产

"\B

asset_params

|asset_id|  some_asset_data |
-----------------------------  
|   1    | 'some data'      |
|   2    | 'some other data'|

现在,我怎样才能找到具有参数的资产,这些参数中有一个名为' Memory'有价值的' 4096'和一个参数OS'有价值的' Windows'。

期望的结果是我在示例中找到一个资产行,ID为1。

我无法找到合理的解决方案。任何帮助表示赞赏。

3 个答案:

答案 0 :(得分:1)

您可以使用聚合和having子句执行此操作:

select asset_id
from asset_params
where param_name = 'Memory' and param_value = '3096' or
      param_name = 'OS' and param_value = 'Windows'
group by asset_id
having count(*) = 2;

注意:如果您可以使用同名的多个参数,则应使用count(distinct param_name) = 2。

这很容易概括。更多Postgres的写作方式是:

select asset_id
from asset_params
where (param_name, param_value) in (('Memory', '3096'),  ('OS', 'Windows'))
group by asset_id
having count(*) = 2;

答案 1 :(得分:1)

这样的事情应该有效:

select * from assets where
    assets_id in (select assets_id from asset_params
        where name = "OS" and value = "Win")
and
    assets_id in (select assets_id from asset_params
        where name = "memory" and value = "4096")

如果你的表很大,这需要适当的索引。但无论如何你应该总是有好的指数。 ;)

答案 2 :(得分:1)

select * from assets a where
    exists (select 1 from asset_params p
        where name = "OS" and value = "Win" and a.asset_id=p.asset_id)
    and exists (select 1 from asset_params p
        where name = "memory" and value = "4096" and a.asset_id=p.asset_id)