Mysql 如何获取不使用';t基于两个不同的表存在
我有以下表格设置: //客户Mysql 如何获取不使用';t基于两个不同的表存在,mysql,Mysql,我有以下表格设置: //客户 +-----------+----------+------------+ | Id | Client | Status | +-----------+----------+------------+ | 1 | A | Active | | 2 | B | Active | | 3 | C | Inactive | +------
+-----------+----------+------------+
| Id | Client | Status |
+-----------+----------+------------+
| 1 | A | Active |
| 2 | B | Active |
| 3 | C | Inactive |
+-----------+----------+------------+
//经理台
+-----------+----------+
| clientId | managerId|
+-----------+----------+
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
+-----------+----------+
//用户表
+-----------+----------+
| id | firstName|
+-----------+----------+
| 1 | Carrera |
| 2 | Taylor |
| 3 | Diaz |
+-----------+----------+
//期望输出
+-----------+----------+
| clientId | managerId|
+-----------+----------+
| 1 | 2 |
| 1 | 3 |
| 2 | 1 |
| 2 | 3 |
+-----------+----------+
如何编写查询以获得所需的输出?我尝试过类似的方法,但结果并不理想:
select c.id as "Client"
, u.id as "user"
from managers cm
left
join users u
on u.id = cm.managerId
left
join clients c
on c.id = cm.clientId
where cm.managerId not in (select id from users where firstName like '%a%')
and cm.clientId not in (select id from clients where status = 'Active');
有趣的想法是
WHERE
子句,因为您需要活动客户机并排除表管理器中的现有连接
客户ID | ManagerId
-------: | --------:
1 | 2
1 | 3
2 | 1
2 | 3
小提琴
CREATE TABLE managers (
`clientId` INTEGER,
`managerId` INTEGER
);
INSERT INTO managers
(`clientId`, `managerId`)
VALUES
('1', '1'),
('2', '2'),
('3', '3');
CREATE TABLE Clients (
`Id` INTEGER,
`Client` VARCHAR(1),
`Status` VARCHAR(8)
);
INSERT INTO Clients
(`Id`, `Client`, `Status`)
VALUES
('1', 'A', 'Active'),
('2', 'B', 'Active'),
('3', 'C', 'Inactive');
CREATE TABLE users (
`id` INTEGER,
`firstName` VARCHAR(7)
);
INSERT INTO users
(`id`, `firstName`)
VALUES
('1', 'Carrera'),
('2', 'Taylor'),
('3', 'Diaz');
SELECT c.`Id` as ClientId ,u.id as ManagerId FROM users u CROSS JOIN Clients c
WHERE c.`Status` = 'Active' AND (u.id,c.`Id`) NOT IN (SELECT `clientId`, `managerId` FROM managers)
ORDER By ClientId,ManagerId
ClientId | ManagerId
-------: | --------:
1 | 2
1 | 3
2 | 1
2 | 3