dongshie8450 2013-06-13 13:22
浏览 13
已采纳

按部门过滤交易

I have a database that is used for recording transactions by customers.

The table (transactions) is set out as follows:

ID | Added-date | userid | amount | department | transaction-date | addedby
1    yyyy-mm-dd   P1001    9.78     dpt 1        yyyy-mm-dd         username
1    yyyy-mm-dd   P1023    19.78    dpt 2        yyyy-mm-dd         username
1    yyyy-mm-dd   P1021    39.78    dpt 3        yyyy-mm-dd         username
1    yyyy-mm-dd   T1501    9.78     dpt 2        yyyy-mm-dd         username

What I would like to do is be able to view all of the users who have never bought anything in department x .

Does anyone have any suggestions as to the best way to go about this?

  • 写回答

3条回答 默认 最新

  • duanpu1064 2013-06-13 13:29
    关注

    There are several ways of doing this. I like the syntax of an OUTER JOIN / NULL check:

    select distinct t.userid
    from transactions t
        left join transactions t2 
            on t.userid = t2.userid and t2.department = 'Some Dept'
    where t2.userid is null
    

    DISTINCT may or may not be needed -- depends on your desired results.

    You could also use NOT IN (but I have seen performance issues in MySQL with this):

    select distinct userid
    from transactions
    where userid not in (
        select userid
        from transactions
        where department = 'Some Dept')
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用