2014-11-24 67 views
1

,我有以下數據集:MySQL的:如果條件滿足串聯2列

CREATE TABLE division (
    id INT AUTO_INCREMENT PRIMARY KEY, 
    division VARCHAR(30) NOT NULL 
) ENGINE=INNODB; 
INSERT INTO division (division) VALUES ("Division1"), ("Division2"), ("Division3"), ("Division4"); 

CREATE TABLE product (
    product_id INT AUTO_INCREMENT PRIMARY KEY, 
    product VARCHAR(30) NOT NULL, 
    divisionID INT 
) ENGINE=INNODB; 
INSERT INTO product (product, divisionID) VALUES ("Product1", 3), ("Product1", 1), ("Product2", 2), ("Product3", 4); 

我有以下查詢:

SELECT Concat(product,' ',division) as 'product' 
FROM products p 
LEFT JOIN division d ON d.id = p.divisionID 
ORDER BY product; 

上面的查詢拉以下記錄:

Product 
------------------ 
Product1 DIvision1 
Product1 Division3 
Product2 Division2 
Product3 Division4 

問:我該如何修改fy查詢,以便只有重複的Products將與它們的Division連接,並且獨特的產品將保持原樣,如下面的示例一樣?

Product 
------------------ 
Product1 Division1 
Product1 Division3 
Product2 
Product3 
+1

做得好提供一個明顯的例子 – Strawberry 2014-11-24 22:32:01

回答

0

這裏是一個非常字面解...

SELECT CONCAT_WS(' ',p.product,CASE WHEN total > 1 THEN d.division ELSE NULL END) name 
    FROM product p 
    LEFT 
    JOIN division d 
    ON d.id = p.divisionid 
    JOIN 
    (SELECT product 
      , COUNT(*) total 
     FROM product 
     GROUP 
      BY product 
    ) x 
    ON x.product = p.product 
ORDER 
    BY p.product,d.division; 
+0

冷靜,謝謝! – alex 2014-11-24 22:46:31