求句SQL,多个分类下查询所属的产品

codeyell-com 2012-02-08 10:35:47
一个产品可以属于多个分类,表结构如下:
goods_id category_id
1 3
1 4
2 3

上面的产品2属于分类3,但产品1,同时属于分类3和4.
如何能查出同时属于多个分类的产品?比如查同时属于分类3和4的产品时,结果只有1.

多谢
...全文
56 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
codeyell-com 2012-02-08
  • 打赏
  • 举报
回复
多谢回复。

select 1 from ...
这个1是什么意思?
ACMAIN_CHM 2012-02-08
  • 打赏
  • 举报
回复
如果条件比较多的话,则可以如下。

select a.* 
from 表结构如下 a
where category_id=3
and exists (select 1 from 表结构如下 where goods_id=a.goods_id and category_id=4)
and exists (select 1 from 表结构如下 where goods_id=a.goods_id and category_id=5)
...
and exists (select 1 from 表结构如下 where goods_id=a.goods_id and category_id=X)
ACMAIN_CHM 2012-02-08
  • 打赏
  • 举报
回复
select a.* 
from 表结构如下 a inner join 表结构如下 b on a.goods_id=b.goods_id
where a.category_id=3 and b.category_id=4
yjl49 2012-02-08
  • 打赏
  • 举报
回复
select goods_id,count(*)
from (
select goods_id,category_id
from mytable
group by goods_id,category_id
) r
group by goods_id
having count(*)>1;

56,677

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧