MySql:如果满足条件,则连接2列

时间:2014-11-24 22:29:39

标签: mysql

我有以下数据集:

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

问:如何修改查询,以便只将重复的Products与其Division连接,并且将保留唯一的产品,如下所示示例

Product
------------------
Product1 Division1
Product1 Division3
Product2
Product3

1 个答案:

答案 0 :(得分: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;