如何为SQL的初学者处理多个查找表?

时间:2013-04-08 06:32:24

标签: mysql sql join

我很难将头围绕在多个查找表中。我有一个中央表,其中包含所有信息,但每列都有ID:

db_supply (Main supplier information data table)
 -----------------------------------------------
| Supplier_ID | Supply_Type_ID | Itm_ID | Stock |
|-----------------------------------------------|
| 1           | 1              | 33     | 3     |
|-----------------------------------------------|
| 2           | 2              | 28     | 1     |
 -----------------------------------------------

lookup_supplier
 -----------------------------
| Supplier_ID | Supplier_Name |
|-----------------------------|
| 1           | Walter        |
|-----------------------------|
| 2           | Jesse         |
 -----------------------------

lookup_supply_type
 -----------------------------------
| Supply_Type_ID | Supply_Type_Name |
|-----------------------------------|
| 1              | Import           |
|-----------------------------------|
| 2              | Delivery         |
 -----------------------------------

lookup_itm
 ------------------------
| Itm_ID | Itm_Name      |
|------------------------|
| 33     | Pickles       |
|------------------------|
| 28     | Burger        |
 ------------------------

A query for 'Burger' will output this table:
 -----------------------------------------------------
| Supplier_Name | Supply_Type_Name | Itm_Name | Stock |
|-----------------------------------------------------|
| Jesse         | Delivery         | Burger   | 1     |
 -----------------------------------------------------

我将如何实现这一目标?到目前为止,我有:

SELECT * FROM db_supply WHERE Itm_ID = (SELECT Itm_ID FROM lookup_itm WHERE Itm_Name = 'Burger')

这会给我db_supply表的第二行,其ID尚未查找。我是否必须嵌套我的选择以查找多个表格?不知道在这里。

2 个答案:

答案 0 :(得分:1)

SELECT  b.Supplier_Name,
        c.Supply_Type_Name,
        d.Itm_Name,
        a.Stock
FROM    db_supply a
        INNER JOIN lookup_supplier b
            ON a.Supplier_ID = b.Supplier_ID
        INNER JOIN lookup_supply_type c
            ON a.Supply_Type_ID = c.Supply_Type_ID
        INNER JOIN lookup_itm d
            ON a.Itm_ID = d.Itm_ID
WHERE   d.Itm_Name = 'Burger'

要进一步了解联接,请访问以下链接:

输出

╔═══════════════╦══════════════════╦══════════╦═══════╗
║ SUPPLIER_NAME ║ SUPPLY_TYPE_NAME ║ ITM_NAME ║ STOCK ║
╠═══════════════╬══════════════════╬══════════╬═══════╣
║ Jesse         ║ Delivery         ║ Burger   ║     1 ║
╚═══════════════╩══════════════════╩══════════╩═══════╝

答案 1 :(得分:0)

请尝试以下查询:

select b.Supplier_Name,c.Supply_Type_Name,d.itemName  from db_supply a,lookup_supplier b,lookup_supply_type c,lookup_itm d where a.Supplier_ID=b.Supplier_ID and a.Supply_Type_ID=c.Supply_Type_ID and a.Itm_ID=d.Itm_ID and d.Itm_Name='Burger'