【问题标题】:One table multiple fields to other table一个表多个字段到另一个表
【发布时间】: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 的回复让我到达了我想要的地方......现在我觉得很愚蠢......我可以在同一个查询中多次调用同一张表......非常感谢您的帮助

标签: mysql sql select mariadb


【解决方案1】:

您可以三次加入employee 表中的product 表,每个角色一次:

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

【讨论】:

  • 就是这样......!!我可以调用同一张桌子的倍数......我现在要把自己关在一个黑暗的房间里......!!非常感谢你的帮助
猜你喜欢
  • 1970-01-01
  • 2020-03-22
  • 1970-01-01
  • 1970-01-01
  • 2018-06-13
  • 1970-01-01
  • 2021-08-11
  • 1970-01-01
  • 2011-08-30
相关资源
最近更新 更多