我需要帮助构建 MYSQL 查询:
主表列出了待售车辆的姓名和地址。
属性(第二)表列出了车辆属性。
如何统计主表中属性表颜色为红色、年份为 2015 年、价格小于 15,000、客户地址为哥伦布的卖家数量?
select count(`master_id`)
from `customers` c
left join `attributes` a
on c.master_id = a.master_id
where (
a.name = 'color' and a.value = 'red' and
a.name = 'year' and a.value = '2015' and
a.name = 'price' and a.value > '15000' and
c.city = 'Columbus';
最佳答案
您可以使用group by
和having
:
select count(*)
from (select master_id
from `customers` c left join
`attributes` a
on c.master_id = a.master_id
where (name, value) in ( ('color', 'red'), ('year', '2015'), ('price', '15000') and
c.city = 'Columbus'
group by a.master_id
having count(distinct name) = 3
) x;
请注意,这使用元组来简化 where
子句。
关于mysql查询计数主表中第二表中具有多个属性的记录数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48896077/