我有下表:
+--------------------+-----------+--------------------+
| 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 |
+--------------------+------------------+--------------------+
我尝试过子选择查询,但在这两种情况下都失败了。
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
问题是子选择返回多行。
最佳答案
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
关于Mysql在同一个查询中使用多个不同的where条件进行多选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25795046/