开发者社区 问答 正文

有关MYSQL并集的问题

一个看似很简单的SQL语句(多对多关系的)[ 基于MYSQL]。
表结构:
user_name product_id
1 A
2 B
1 B
3 C
4 C
1 D
需求:哪些用户同时购买了 A,C,D?(或者说,同时购买A,C,D的用户都是那些?)
要求有极高的效率 一句sql解决

展开
收起
落地花开啦 2016-02-12 16:36:43 2531 分享 版权
2 条回答
写回答
取消 提交回答
  • 公益是一辈子的事, I am digoal, just do it. 阿里云数据库团队, 擅长PolarDB, PostgreSQL, DuckDB, ADB等, 长期致力于推动开源数据库技术、生态在中国的发展与开源产业人才培养. 曾荣获阿里巴巴麒麟布道师称号、2018届OSCAR开源尖峰人物.

    这个需求,用PostgreSQL的聚合查询可以非常简单的实现,而且效率非常高,比多表关联效率高太多了。

    postgres=# create table t(id int, info text);
    CREATE TABLE
    postgres=# insert into t values (1,'a'),(1,'b'),(1,'c'),(1,'d'),(2,'a'),(2,'c'),(3,'d');
    INSERT 0 7
    postgres=# select id from t group by id having array_agg(info) @> array['a','c'];
     id 
    ----
      1
      2
    (2 rows)
    2019-07-17 18:41:30
    赞同 展开评论
  • 喜欢技术,喜欢努力的人

    `select a.user_name from table a, table b, table c
    where a.product_id='A' and b. product_id='B' and c.product_id='C'
    and a.user_id=b.user_id and b.user_id=c.user_id;`
    或者用全文检索。

    2019-07-17 18:41:30
    赞同 展开评论