Mysql在同一个查询中使用多个不同的where条件进行多选

标签 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               |
+--------------------+------------------+--------------------+

我尝试过子选择查询,但在这两种情况下都失败了。

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 

问题是子选择返回多行。

最佳答案

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

关于Mysql在同一个查询中使用多个不同的where条件进行多选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25795046/

相关文章:

android - 如何从 Android 连接 phpmyadmin

mysql - 如果MySQL中未满足 "where",如何返回具有不同值的行

mysql - 如果右字段存在,左连接如何使用

sql - 查询中的查询 : Is there a better way?

sql - 引用 QueryDSL 中的子查询字段

sql - 错误: 'duplicate key value violates unique constraint' even when checking with 'where not in'

mysql - SQL Duplicates - 没有找到所有的

sql - 为什么这个 MySQL 查询在向表中插入值时给出 "error 1136"

mysql - 使用 Select Dateadd() sql server 减去年份

php - mysql通过外键将主表与另一个表连接