多表查询 - SQL

时间:2013-06-20 11:47:48

标签: mysql sql

我是mysql的新手,所以我还不知道如何连接多个表进行查询,所以我需要一些帮助才能进行此查询。

所以我有这些表:

产品

| id         | category    | description  |    brand     |
|:-----------|------------:|:------------:|:------------:|
| 1          |    desktops |    Hp example|     HP       |
| 2          |    laptops  |  asus example|       ASUS   |

商店

| id         | location    | Brands(physical stores) | 
|:-----------|------------:|:-----------------------:|
| 1          |    liverpool|    currys               |    
| 2          |    london   | novatech                | 
| 3          |    bristol  | novatech                | 

products_stores

| id_product | id_store    | price   | 
|:-----------|------------:|:-------:|
| 1          |    2        |    700  |    
| 2          |    3        |   400   | 
| 2          |    1        |   300   | 

所以,我想要一个查询来获取数据并像这样组织它(假设我想要所有数据):

| category    | description  |    brand     |   store      |  location  |   price   |
|:------------|-------------:|:------------:|:------------:|:----------:|:---------:|
|    desktops |    Hp example|     HP       |    novatech  |  london    |   700     |
|    laptops  |  asus example|       ASUS   |    novatech  |  bristol   |   400     |
|    laptops  |  asus example|       ASUS   |    currys    |  liverpool |   300     |

3 个答案:

答案 0 :(得分:1)

select products.category, products.description, products.brand, stores.brands, stores.location, products_stores.price
from products_stores
inner join stores on stores.id = products_stores.stores_id
inner join products on products.id = products_stores.products_id

sql fiddle

答案 1 :(得分:1)

只需使用joins(更具体地说是INNER JOIN,并确保store列不会被称为Brands(physical stores)。如果它被称为brands,那么只需在查询中更改它:

SELECT
    pr.category,
    pr.description,
    pr.brand,
    st.store,
    st.location,
    ps.price
FROM
    `products_stores` as `ps`
INNER JOIN
    `products` as `pr`
ON
    pr.id = ps.id_product
INNER JOIN
    `stores` as `st`
ON
    st.id = ps.id_store

答案 2 :(得分:1)

SELECT p.category, p.description, p.brand, s.Brands as store, s.location, ps.price 
    FROM Products p, Stores s, products_stores ps 
         WHERE p.id = ps.id_product AND s.id = ps.id_store;

使用以上查询。