SQL Join与子查询

时间:2016-05-17 07:35:39

标签: mysql sql

我正在运行MySQL 5.1.71。在我的数据库中有三个表 - load,brass和mfg,load是我的“主”表。我的目标是查询加载并在结果中包含mfg.name。我已经尝试了JOIN子句与子查询的各种迭代,包括和不包含WHERE子句。这似乎应该是非常微不足道的,所以我不确定我怎么也达不到解决方案。

load
-------------------------
| id | desc  | brass_id |
-------------------------
|  1 | One   |        2 |
|  2 | Two   |        1 |
-------------------------

brass
---------------
| id | mfg_id |
---------------
|  1 |      6 |
|  2 |      8 |
---------------

brass_mfg
------------------------
| id | name            |
------------------------
|  6 | This Company    |
|  8 | That Company    |
------------------------

我想要的结果将是......

results
---------------------------
| load  | mfg             |
---------------------------
| One   | That Company    |
| Two   | This Company    |
---------------------------
  • 加载ID始终只有一个黄铜ID
  • 黄铜ID始终只有一个制造商ID



修改
之前提供的示例数据(上图)已更新。另外,下面是我正在运行的查询以及我得到的结果。公司在返回的每条记录中都是错误的。我已经在查询和结果中包含了表中的ID。显示的公司名称不是mfg表中ID的名称。

SELECT 
    load.id AS "load.id", 
    load.brass_id AS "load.brass_id", 
    brass.id AS "brass.id", 
    brass.mfg_id AS "brass.mfg_id", 
    brass_mfg.id AS "brass_mfg.id", 
    brass_mfg.name AS "brass_mfg.name" 
FROM `load`
LEFT JOIN brass ON load.brass_id = brass.id
LEFT JOIN brass_mfg ON brass.id = brass_mfg.id 


-----------------------------------------------------------------------------------------
| load.id | load.brass_id | brass.id | brass.mfg_id | brass_mfg.id | brass_mfg.name     |   
-----------------------------------------------------------------------------------------
| 1       | 2             | 2        | 6            | 2            | Wrong Company      |
| 2       | 1             | 1        | 8            | 1            | Incorrect Company  |
-----------------------------------------------------------------------------------------

3 个答案:

答案 0 :(得分:2)

查看您的表格,看看哪些数据彼此相关,然后逐个表格建立联接,以获得所需的输出。

SELECT p.desc AS Product, m.name AS mfg
FROM product p
INNER JOIN lot l ON p.lot_id = l.id
INNER JOIN mfg m ON l.mfg_id = m.id

答案 1 :(得分:0)

您的加入查询中有错误。 试试这个:

LEFT JOIN

enter image description here

您只需要{{1}}

答案 2 :(得分:0)

如果这是单一关系,为什么要有中间表? 在您的情况下,最好的方案是简单连接。

SELECT pt.desc as Product, mfg.name as Mfs
FROM Product pt
Join Lot lt on lt.id = pt.lot_id
Join Mfg mf on mf.id = lt.mfg_id