【发布时间】:2017-08-09 15:03:34
【问题描述】:
所以我有一个包含所有用户信息的表和另一个包含产品信息的表。
在每个产品上都有对多个用户的引用。 例如:user1 是生产者,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
)
【问题讨论】:
-
select product_id, user1.name, user2.name, user3.name left join users on product.user1_id = users.user_id user1 left join users on product.user2_id = users.user_id user2 left join users on product.user3_id = users.user_id user3 where product_id = ? -
或其他东西 - 正如@ryanVincent 所说,如果我们知道查询应该是什么样子,那么提供帮助会容易得多:)
-
我还没有插入任何数据....我仍在尝试将头绕在结构上...知道是否需要更改结构。但我找不到让查询有意义的方法。
-
@Mureinik 的回复让我到达了我想要的地方......现在我觉得很愚蠢......我可以在同一个查询中多次调用同一张表......非常感谢您的帮助