douyuefei3546 2015-09-07 14:08
浏览 111
已采纳

如何从mysql内连接查询中过滤结果

I have got a problem with my many to many relationship.

Client table columns: clientID, name, address etc.

User table columns: userID, name, address etc.

Users_clients columns: userID, clientID.

Each client can have multible users attached and users can have multible clients.

Right now my users_clients table contains this:

userID | clientID<br>
1      | 2
1      | 3
2      | 2
2      | 3
3      | 3
3      | 2
4      | 1

On my php page I want a list of users which is not already attached to the client.

Ex. if I click on the client profile which has clientID = 3 It should show me a list of users not attached to this client.

SELECT u.name, u.email, u.userID FROM users u
  INNER JOIN users_clients uc
    ON u.userID = uc.userID 
  WHERE uc.clientID !=3

This works fine, but how do I create my MySQL query so that if a user have both clientID 3 and client 2 it doesn't show.

This query shows

1|2 2|2 3|2 4|1

and what I'm seeking is:

3|2 4|1

Hope this makes sense to you. Feel free to ask :)

  • 写回答

2条回答 默认 最新

  • duanmianhong4893 2015-09-07 14:22
    关注

    You could process differently.

    First make a request to seek every user with a clientId = 3;

    select u.id from users u
    INNER JOIN users_clients uc
    ON u.userID = uc.userID 
    WHERE uc.clientID =3;
    

    And then you could use this request to fetch all the users except those who have a clientId = 3.

    Final request looks like this :

    select u.id from users u where u.id NOT IN (select u.id from users u
    INNER JOIN users_clients uc
    ON u.userID = uc.userID 
    WHERE uc.clientID =3);
    

    hope this'll help;

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 vue3加ant-design-vue无法渲染出页面
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序