MYSQL 多个引用 table

MYSQL multiple joins with reference table

我不知疲倦地研究,试图理解 mysql 与多个 table 的连接以及参考 table 是如何发挥作用的,但无济于事。这也是我的第一个 post 如果我错过任何规则,请保持温和。

这是我的 tables:

customers | CREATE TABLE `customers` (
  `customer_num` int(11) NOT NULL AUTO_INCREMENT,
  `customer_name` varchar(50) DEFAULT NULL,
  `city` varchar(50) DEFAULT NULL,
  `state` varchar(50) DEFAULT NULL,
  `country` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`customer_num`)

orders | CREATE TABLE `orders` (
  `order_num` int(11) NOT NULL AUTO_INCREMENT,
  `order_date` date DEFAULT NULL,
  `shipped_date` date DEFAULT NULL,
  `status` varchar(15) DEFAULT NULL,
  `comments` text,
  `customer_num` int(11) DEFAULT NULL,
  PRIMARY KEY (`order_num`)

p_o   | CREATE TABLE `p_o` (
  `product_num` int(10) unsigned NOT NULL,
  `order_num` int(10) unsigned NOT NULL,
  KEY `order_num` (`order_num`)

 products | CREATE TABLE `products` (
  `product_num` int(11) NOT NULL AUTO_INCREMENT,
  `year` int(4) unsigned NOT NULL DEFAULT '2014',
  `make` varchar(20) NOT NULL,
  `model` varchar(20) NOT NULL,
  `price` int(6) NOT NULL DEFAULT '0',
  PRIMARY KEY (`product_num`)

客户与订单是一对多关系,而订单引用 p_o,它同时具有 product_num 和 order_num,并且 p_o 也连接到产品。

我的目标是进行一个查询(在某种程度上是最优的,不是所有的选择和位置),它将在一个 table 中显示所有这些信息。我创建了这个但无法让他们显示超过两个 table 的信息。

select * from customers t1 join orders t2 on t1.customer_num=t2.customer_num;

该联接显示了来自订单和客户的所有信息,我打算将其作为内部联接。我已经尝试了各种方法让他们都加入到一个,但他们都没有工作,我相信这是我的结束。另外,我使用的模块可以生成动态 mysql tables 并且不支持联合,但即使您有使用联合的解决方案,我也会接受它。

非常感谢您提供的任何帮助,我已经为此工作了太多时间。

我认为您应该使用以下方法获取所需的信息:

SELECT  
  `orders`.`order_num`,
  `orders`.`order_date`,
  `orders`.`shipped_date`,
  `orders`.`status`,
  `orders`.`comments`,
  `orders`.`customer_num`,
  `customers`.`customer_name`,
  `customers`.`city`,
  `customers`.`state`,
  `customers`.`country`,
  `products`.`product_num`,
  `products`.`year`,
  `products`.`make`,
  `products`.`model`,
  `products`.`price`
FROM
    `orders`
    inner join `customers`
        ON `customers`.`customer_num` = `orders`.`customer_num`
    inner join `p_o`
        ON `p_o`.`order_num` = `orders`.`order_num`
    inner join `products`
        ON `products`.`product_num` = `p_o`.`product_num`

我想(也希望)能帮助您理解基于这个问题的multiple join的过程。

这个多重连接操作的 in-words 描述可能是这样的:


我需要提取有关订单的详细信息,即:订单 header 信息、订单客户详细信息和每个订单号内订购的产品。
根据我的数据库结构,我可以看到来自 orders table 的每个订单 header 都有包含订单所属客户编号的字段,所以我想连接来自 [=12] 的详细数据=] table 来自 orders table.
的每个订单 然后我知道我还需要每个特定订单的每个产品的详细规格。
我的数据库结构表明我可以从 products table 到 "connection" table p_o 访问产品详细信息,然后我将 p_o 连接到我的already-joined 设置 {customers, orders} 基于 order_num 列。
现在在结果集中有了这些信息 ({customers, orders, p_o}) 我只需要连接 products table 到 product_code 键上的 p_o table。
最后,我列出了最终结果集中所需的列,这些列由四个 tables {customersordersp_oproducts 组成}.


希望对您有所帮助。