2013-06-20 58 views
1

我有點新來的MySQL,所以我不知道如何使querys加入多個表,所以我需要一些幫助使這個查詢。多表查詢 - SQL

所以我有這些表:

產品

| 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 | 

所以,我要查詢來獲取數據,並組織其喜歡這個( suposing我想所有數據):

| 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  | 

回答

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

只需使用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 
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; 

使用上面的查詢。