我的数据库非常简单:
CREATE TABLE Account (
accountId int NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
PRIMARY KEY (accountId)
);
CREATE TABLE Manager (
managerId int NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
PRIMARY KEY (managerId)
);
CREATE TABLE ManagerAccount(
id int not null auto_increment,
managerId int not null,
accountId int not null,
primary key(id),
foreign key(managerid) references Manager (ManagerID),
foreign key(accountId) references Account (AccountID)
);
现在,当我向用户返回一个帐户对象时,我需要提取与特定帐户相关联的所有帐户
所以我做了类似的事情:
select m.name
from manager m
inner join ManagerAccount ma on m.managerId = ma.id
inner join Account a on ma.id = a.accountId
where a.accountId = 1;
但这并没有给我我想要的答案,我只获得一个经理名称,并且有3个经理与accountId 1相关联...
你可以在这里看到:答案 0 :(得分:3)
inner join ManagerAccount ma on m.managerId = ma.id
inner join Account a on ma.id = a.accountId
应该是
inner join ManagerAccount ma on m.managerId = ma.managerId
inner join Account a on ma.accountId = a.accountId
答案 1 :(得分:0)
在您的查询中,您具有ManagerAccount.accountId与Account(AccountID)的外键关系。 但是您已将ManagerAccount表的主键映射到Account(AccountID)。
SELECT
m.name
FROM
Manager m
INNER JOIN
ManagerAccount ma ON m.managerId = ma.managerId
INNER JOIN
Account a ON ma.accountId = a.accountId
WHERE
a.accountId = 1;