正在查找MySQL/MariaDB,其中查询多行

7fhtutme  于 2022-11-08  发布在  Mysql
关注(0)|答案(2)|浏览(133)
Table Products
ad_id| property_id | property_value_id
69          4           1
69          7           6
69          6           3
67          7           6
...

例如:
我需要搜索((其中属性标识= 4且属性值标识= 1)和(其中属性标识= 7且属性值标识= 6))
结果应为:69
IM搜索的值是动态的。

bjp0bcyl

bjp0bcyl1#

SELECT DISTINCT ad_id
FROM
    (SELECT ad_id
    FROM Producst
    WHERE (property_id = 4 AND property_value_id = 1)
      OR  (property_id = 7 AND property_value_id = 6)
      OR  (property_id = 6 AND property_value_id = 3)
    group by ad_id
    having count(ad_id) = 3) as subquery

应该做的工作。

rslzwgfq

rslzwgfq2#

您可以将表格与其本身链接三次,每对搜寻值链接一次。查询的格式如下:

select distinct a.ad_id
from my_table a
join my_table b on b.ad_id = a.ad_id
join my_table c on c.ad_id = a.ad_id
where a.property_id = 4 and a.property_value_id = 1
   or b.property_id = 7 and b.property_value_id = 6
   or c.property_id = 6 and c.property_value_id = 3

相关问题