Mysql多次选择具有多个不同where条件的同一查询

时间:2014-09-11 18:53:19

标签: mysql where-clause subquery multiple-select

我有下表:

+--------------------+-----------+--------------------+
| Product            | website   | is_master          |
+--------------------+-----------+--------------------+
| product A          |       X   | 1                  |
| product A          |       Y   | 0                  |
| product A          |       Z   | 0                  |
| product A          |       C   | 0                  |
| product B          |       D   | 1                  |
| product C          |       E   | 1                  |
+--------------------+-----------+--------------------+

我正在尝试创建一个mysql查询来获取表a,如下所示:

+--------------------+------------------+--------------------+
| Product            | master_website   | additional_sites   |
+--------------------+------------------+--------------------+
| product A          |       X          | y,z,c              |
| product B          |       D          | null               |
| product C          |       E          | null               |
+--------------------+------------------+--------------------+

我尝试过使用subselect查询但在两种情况下都失败了。

select 
Product, 
    (select Product 
     FROM `table1` 
     LEFT JOIN 
     table2 on table1.id = table2.fk_table1 
     WHERE is_master = 1) is_master, 

    (select group_concat(Product) 
     FROM `table1` 
     LEFT JOIN 
     table2 on table1.id = table2.fk_table1 
     WHERE is_master = 0) additional 

     FROM `table1` 
     LEFT JOIN 
     table2 on table1.id = table2.fk_table1 

WHERE 1 
group by 
Product 

问题是subselect返回多行。

2 个答案:

答案 0 :(得分:2)

SQL Fiddle

SELECT t1.Product,
          t1.website AS master_website, 
          GROUP_CONCAT(t2.website ORDER BY t2.website) AS additional_sites   
     FROM MyTable t1
LEFT JOIN MyTable t2 
       ON t1.Prduct = t2.Prduct AND 
          t2.is_master = 0
    WHERE t1.is_master = 1
 GROUP BY t1.Product

答案 1 :(得分:0)

你可以在2个子选择1中打破你的连接查询,每个产品只选择一个记录,其中is_master = 1,我假设每个产品只有1行is_master = 1,第二个子选择将选择is_master = 0然后使用左连接进行子选择

SELECT t.*,t1.additional FROM 
(SELECT 
Product,
website AS is_master, 
FROM `table1` 
LEFT JOIN 
table2 ON table1.id = table2.fk_table1 
WHERE is_master = 1 
) t
LEFT JOIN 
(
  SELECT Product ,GROUP_CONCAT(website) additional
  FROM `table1` 
  LEFT JOIN table2 ON table1.id = table2.fk_table1 
  WHERE is_master = 0 
  GROUP BY Product
) t1 ON(t.Product = t1.Product)