2016-04-30 77 views
5

MySQL從3個表中選擇。MySQL從3個表中選擇不同的產品

我有這些5個表:

CREATE TABLE `category` (
    `c_id` int(6) NOT NULL AUTO_INCREMENT, 
    `name` varchar(40) NOT NULL, 
    PRIMARY KEY (c_id) 
); 

CREATE TABLE `product` (
    `p_id` int(11) NOT NULL AUTO_INCREMENT, 
    `name` varchar(40) NOT NULL, 
    `brand` varchar(30) NOT NULL, 
    `image_path` varchar(100) DEFAULT NULL, 
    PRIMARY KEY (p_id) 
); 

CREATE TABLE `shop` (
    `s_id` int(6) NOT NULL AUTO_INCREMENT, 
    `name` varchar(50) NOT NULL, 
    `country` varchar(30) NOT NULL, 
    `province` varchar(30) NOT NULL, 
    `city` varchar(30) NOT NULL, 
    `suburb` varchar(30) NOT NULL, 
    `street` varchar(40) DEFAULT NULL, 
    `streetNumber` varchar(40) DEFAULT NULL, 
    `postalCode` int(4) DEFAULT NULL, 
    PRIMARY KEY (s_id) 
) ; 

CREATE TABLE product_category (
p_id INT NOT NULL, 
c_id INT NOT NULL, 
PRIMARY KEY (p_id, c_id), 
FOREIGN KEY (p_id) REFERENCES Product(p_id) ON UPDATE CASCADE, 
FOREIGN KEY (c_id) REFERENCES Category(c_id) ON UPDATE CASCADE 
); 

CREATE TABLE product_shop (
p_id INT NOT NULL, 
s_id INT NOT NULL, 
PRIMARY KEY (p_id, s_id), 
FOREIGN KEY (p_id) REFERENCES product(p_id) ON UPDATE CASCADE, 
FOREIGN KEY (s_id) REFERENCES shop(s_id) ON UPDATE CASCADE 
); 

基本上,產品可以有很多類別。一個類別可以分配給許多產品。一家商店可以有很多產品。產品可以在許多商店。

我想選擇其中category.c_id = 2,或category.c_id = 8和shop.s_id = 1個或shop.s_id = 2

我部分的方式有與此所有產品:

select * 
from product inner join product_category 
on product_category.p_id=product.p_id 
where (product_category.c_id=2) 
or (product_category.c_id=8) 

這得到所有有2個,也一個大類產品編號爲8的類別編號的產品,但它得到了相同的產品兩次,如果它既有category.c_id = 8,category.c_id = 2.

然後我試着讓它獲得獨特的產品:

select DISTINCT(product.p_id) as product 
from product inner join product_category 
on product_category.p_id=product.p_id 
where (product_category.c_id=2) 
or (product_category.c_id=8) 

這是現在截然不同,但沒有顯示足夠的產品或類別的信息。我想在每一行中顯示儘可能多的信息。

而下一步是隻獲取那些在shop.s_id = 1個或shop.s_id = 2

誰能幫我那裏還是更接近?謝謝!

+0

嘗試'SELECT DISTINCT *'或'SELECT DISTINCT col1,col2 ...' –

回答

2

假設您想要列出所有產品信息。如果您不希望產品重複,則可以使用IN子句。現在

select p.* 
from product p 
where p.p_id in (select c.p_id from product_category c where c.c_id in (2,8)) 
    and p.p_id in (select s.p_id from product_shop s where s.s_id in (1,2)) 

,如果你想要的類別和店鋪的產品涉及到所有產品數據和列表,然後你可以使用加入和一些非常方便的功能。

select p.p_id, p.`name`, p.brand, GROUP_CONCAT(DISTINCT c.c_id SEPARATOR ', ') as categories, GROUP_CONCAT(DISTINCT s.s_id SEPARATOR ', ') as shops 
from product p inner join product_category c on p.p_id = c.p_id 
       inner join product_shop s on p.p_id = s.p_id 
where c.c_id in (2,8) 
    and s.s_id in (1,2) 
group by p.p_id, p.`name`, p.brand 
+0

謝謝!出於某種原因,它顯示在一個產品的結果行中,用於類別和商店: 2,8,8,2 1,2,1,2例如,它有一個產品的重複商店和類別。我已經在我的product_category表中發佈了一張照片...我在那裏做錯了什麼,這是否讓它重複了單個產品的類別和商店? – BeniaminoBaggins

+0

發生這種情況是因爲該產品在2個商店中存在,並且與2個類別相關:2 x 2 =產品出現4次。解決方案是在group_concat上添加獨特的。看到我的答案編輯。 –