繁体   English   中英

MySQL:查询一对多表?

[英]mySQL: Querying one-to-many -table?

在下面的数据库设计中,采用一对多方法查询具有特定属性的产品的合适方法是什么?

我想我应该做以下事情: SELECT (*) FROM productProperties WHERE property = 'weight' AND value = '10'

但是,如果我需要在同一查询中同时权重= 10和颜色=蓝色的产品怎么办?

数据库设计示例:

表:产品

------------------------
id    | name     |  price
------------------------
0     | myName   |  100
1     | myName2  |  200

表:productProperties

------------------------------------------------
product  | property     |  Value
------------------------------------------------
0        | weight       |  10
1        | weight       |  20
1        | color        |  blue

如果我需要在同一查询中同时权重= 10和颜色=蓝色的产品怎么办?

一种选择:

select product, name
  from products inner join productProperties
    on (products.id = productProperties.product)
 where (property = 'weight' and value = '10')
    or (property = 'color' and value = 'blue')
 group by product, name
having count(1) = 2

子查询的另一种选择:

select id, name
  from products p
 where exists (
         select 1
           from productProperties pp1
          where p.id = pp1.product 
            and pp1.property = 'weight'
            and value = '10'
       )
   and exists (
         select 1
           from productProperties pp2
          where p.id = pp2.product 
            and pp2.property = 'color'
            and value = 'blue'
       )
SELECT * FROM productProperties p 
WHERE (SELECT COUNT(*) FROM productProperties p1 WHERE p1.product = p.product AND 
( (property = 'weight' AND value = '10') OR (property = 'color' AND value = 'blue') ) 
 =2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM