具有三个表的MYSQL pivot返回NULL

具有三个表的MYSQL pivot返回NULL,mysql,join,many-to-many,Mysql,Join,Many To Many,搜索并没有给出任何结果,因为并没有办法让问题变得更加模糊。 我有这样一个db: CREATE TABLE users (`id` int, `name` varchar(4)) ; INSERT INTO users (`id`, `name`) VALUES (1, 'john'), (2, 'jane'), (3, 'max') ; CREATE TABLE agents (`id` int, `title` varchar(25)) ;

搜索并没有给出任何结果,因为并没有办法让问题变得更加模糊。 我有这样一个db:

CREATE TABLE users
    (`id` int, `name` varchar(4))
;

INSERT INTO users
    (`id`, `name`)
VALUES
    (1, 'john'),
    (2, 'jane'),
    (3, 'max')
;

CREATE TABLE agents
    (`id` int, `title` varchar(25))
;

INSERT INTO agents
    (`id`, `title`)
VALUES
    (1, 'APERTURE'),
    (2, 'MESA')
;

CREATE TABLE pivot
    (`contractid` int, `userid` varchar(4), `agentid` varchar(4))
;

INSERT INTO pivot
    (`contractid`, `userid`, `agentid`)
VALUES
    (1, '1', '1'),
    (1, '2', NULL),
    (2, NULL, '1'),
    (2, '2', NULL)
;

CREATE TABLE contracts
    (`id` int, `number` varchar(3), `restricted` int)
;

INSERT INTO contracts
    (`id`, `number`, `restricted`)
VALUES
    (1, 'one', 1),
    (2, 'two', 0)
;
当我提出这样的问题时:

select contracts.*, agents.title from pivot
left join users on pivot.userid = users.id
left join agents on pivot.agentid = agents.id
left join contracts on pivot.contractid = contracts.id
where users.id = 2
它回来了

ID| NUMBER  |RESTRICTED|    TITLE|

1 | one     |     1    |   (null)|

2 | two     |   0      |   (null)|
我知道这是因为不正确的连接,返回NULL是因为在数据透视表中,userid是2->agentid是NULL

如何以正确搜索并返回所有所需数据的方式进行查询。 非常感谢

编辑:我希望得到与此查询相同的结果

select contracts.*, users.id, agents.title from contracts
left join pivot on contracts.id = pivot.contractid
left join agents on pivot.agentid = agents.id
left join users on pivot.userid = users.id

where pivot.contractid in (
  select pivot.contractid from pivot where pivot.userid = 2
)
哪个会回来

ID  NUMBER  RESTRICTED  TITLE
1   one        1       APERTURE
1   one        1       (null)
2   two        0       APERTURE
2   two        0       (null)

但在上面的查询方式中,因为它是根据脚本的结果进行查询的,我不能使用提供的查询,在

中,您希望从SQL查询中获得什么?这似乎是对的。。但是我不明白你想要什么

在WHERE子句中对USER_ID=2使用filter后,您将只获得行,其中pivot中的USER_ID=2为TRUE:因此您将获得代理_ID为NULL的两行。。。看起来还可以。。若要查看标题,应将其添加到表透视中

后编辑:

select c.*
, u.id
, a.title
##
from pivot p
##
left join contracts c
ON c.id = p.contractid
##
left join agents a
on p.agentid = a.id
##
left join users u
on p.userid = u.id
##
where 1=1

这给了我与您的查询相同的结果

先生,请在编辑后查看我的问题。有什么想法吗?