mysql - 我需要完美的 mysql 查询来获得我想要的结果

标签 mysql

我在 http://sqlfiddle.com/#!9/b6015c6/2 创建了 sql fiddle

我的表架构如下:

> assignedattributeid (TABLE)
>     id INT(10)
>     productid INT(10)
>     attributeid INT(10)
> 
> products (TABLE)
>     id INT(10)
>     productname VARCHAR(50)

假设记录如下:

表 : assignedattributeid

id  productid   attributeid
1   5   10
2   5   11
3   6   11
4   7   10

表:产品

id  productname
5   P1000
6   P2000
7   P3000

实际上我想获得所有那些同时分配了 attributeid 10 和 11 的产品。

I use this query : select distinct products.* from products left join assignedattributeid on assignedattributeid.productid=products.id where assignedattributeid.attributeid in (10,11)

但它不起作用。它显示所有记录。实际上它应该只显示 P1000 产品。

有什么建议吗?

最佳答案

按产品分组并添加一个 HAVING 条件来计算唯一的 attributeids - 它必须是 2。

select products.* from  products
join assignedattributeid on assignedattributeid.productid=products.id
where assignedattributeid.attributeid in (10,11)
group by products.id
having count(distinct assignedattributeid.attributeid) = 2

http://sqlfiddle.com/#!9/b6015c6/11

或者为每个attributeid加入一次assignedattributeid

select distinct products.* from  products
join assignedattributeid a1 on a1.productid=products.id
join assignedattributeid a2 on a2.productid=products.id
where a1.attributeid = 10
  and a2.attributeid = 11

http://sqlfiddle.com/#!9/b6015c6/8

如果 products.id 是主键并且 assignedattributeid(productid, attributeid) 是唯一键,则不需要 DISCTINCT关键字。

关于mysql - 我需要完美的 mysql 查询来获得我想要的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38802853/

相关文章:

javascript - 如何将动态添加的内容存储到数据库

php - 变量在 else 中不起作用

php - 插入到基于数组的表中

mysql - 为什么这个 MySQL 查询在条件组合时慢,但在条件分离时快?

java - 我想制作搜索框以通过android studio从mysql获取数据

mysql - #1064 - 创建 View 时 SQL 语法有错误

如果不在当前表中,mysql 从存档表中选择数据

mysql - 如何获得具有最大值的不同行

mysql - 如何合并和删除新数据库上的现有主键?

php - 测试PHP/jQuery/xHTML/CSS程序员…设置实时多用户(安全?)测试环境的最佳方法