1

我是 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     |
4

3 回答 3

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小提琴

于 2013-06-20T11:50:11.807 回答
1

只需使用连接(更具体地说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
于 2013-06-20T11:51:47.253 回答
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;

使用上面的查询。

于 2013-06-20T11:51:59.540 回答