代码之家  ›  专栏  ›  技术社区  ›  acme

MySQL:多次搜索单个表?

  •  1
  • acme  · 技术社区  · 17 年前

    id entry_id property value
    1 12 color blue
    2 12 shape circle
    3 13 color red
    4 13 shape circle
    5 14 color blue
    6 14 shape square
    7 15 material stone
    8 12 material plastic

    现在我想在这个表中搜索属性,比如选择 颜色 是

    select entry_id from table where property = 'color' and value = 'blue'

    到目前为止,一切顺利。但是,当我有多个条件时,如何展开查询?例如,我想搜索所有条目,其中 颜色 是 蓝色 形状 . 现在我要通过工会来实现这一点:

    select entry_id from table where property = 'color' and value = 'blue'
    union
    select entry_id from table where property = 'shape' and value = 'circle'

    我想找的房产越多,这显然就越难看。我认为它也不是很快。有没有更优雅的方法?创建此表的原因是,我有可以由用户设置的元数据对象。

    非常感谢。

    3 回复  |  直到 17 年前
        1
  •  1
  •   John Boker    17 年前

    这就是你要找的吗?

    select 
      distinct e1.entry_id 
    from 
     table e1 
    inner join
      table e2 on e1.entry_id=e2.entry_id 
    where 
      e1.property='color' and 
      e1.value='blue' and 
      e2.property='shape' and 
      e2.value='circle'
    
        2
  •  0
  •   John Kugelman Michael Hodel    17 年前
    SELECT a.entry_id
    FROM   table a INNER JOIN table b USING (entry_id)
    WHERE  a.property = 'color' AND a.value = 'blue'
       AND b.property = 'shape' AND b.value = 'circle'
    
        3
  •  0
  •   Eric    17 年前

    union 或 or

    select distinct
        entry_id
    from
        table t
        inner join 
            (select 'shape' as property, 'circle' as value
             union all
             select 'color' as property, 'blue' as value) s on
            t.property = s.property
            and t.value = s.value
    

    你也可以试试 exists :

    select distinct 
        entry_id
    from
        table t
    where
        exists (select 1 from 
                    (select 'shape' as property, 'circle' as value
                     union all
                     select 'color' as property, 'blue' as value) s
               where 
                   s.property = t.property
                   and s.value = t.value)
    

    union all 到 s

    推荐文章