所以我有一个包含所有用户信息的表和另一个包含产品信息的表。
在每个产品上都有对多个用户的引用。 例如:user1是producer,user2是productSupervisor,user3是productManager。
我如何获得这样的信息: product1.producer是User1.Name,product1.supervisor是user2.Name,product.manager是user3.Name
producer,productSupervisor和productManager存储为userID。
创建语句
CREATE TABLE employee (
idEmployee int(11) NOT NULL AUTO_INCREMENT,
networkID varchar(45) NOT NULL,
firstName varchar(100) NOT NULL,
lastName varchar(100) NOT NULL,
phoneExtension varchar(10) DEFAULT NULL,
email varchar(50) NOT NULL,
mobile varchar(20) DEFAULT NULL,
onCall tinyint(4) NOT NULL DEFAULT '0',
lastLogin varchar(100) DEFAULT 'Never',
active tinyint(4) NOT NULL DEFAULT '1',
createDate timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (idEmployee),
KEY idx_employee (idTeam),
KEY idx_employee_0 (idPosition),
CONSTRAINT fk_employee_employeepositions FOREIGN KEY (idPosition) REFERENCES employeePositions (idPosition) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT fk_employee_teams FOREIGN KEY (idTeam) REFERENCES teams (idTeam) ON UPDATE NO ACTION
)
CREATE TABLE product (
idProduct int(11) NOT NULL,
idSupervisor int(11) NOT NULL DEFAULT '1',
idProducer int(11) NOT NULL DEFAULT '1',
idManager int(11) NOT NULL DEFAULT '1',
prodcutInfo longtext,
PRIMARY KEY idProduct
)
答案 0 :(得分:1)
您可以在product
表上加入employee
表三次,每个角色一次:
SELECT idProduct,
CONCAT_WS(' ', s.firstname, s.lastname) AS supervisor,
CONCAT_WS(' ', p.firstname, p.lastname) AS producer,
CONCAT_WS(' ', m.firstname, m.lastname) AS manager
FROM product pr
JOIN employee s ON pr.idSupervisor = s.idEmployee
JOIN employee p ON pr.idSupervisor = p.idEmployee
JOIN employee m ON pr.idSupervisor = m.idEmployee