简体   繁体   English

MySQL内部连接或左连接

[英]Mysql inner join or left join

I have 1 table products and I would like to extract price of products with type A and B. I try to use INNER JOIN but it returns duplicate record. 我有1个表产品,我想提取类型A和B的产品价格。我尝试使用INNER JOIN,但它返回重复的记录。 How can I do this? 我怎样才能做到这一点?

 id   |   Price    |     Date    |   Type   |   Size  |
-------------------------------------------------------
 1    |   1,00     |  01/11/2010 |     A    |   7,00  |
 2    |   2,50     |  02/11/2010 |     A    |   8,00  |
 3    |   2,50     |  03/11/2010 |     A    |   9,00  |
 4    |   3,00     |  02/11/2010 |     A    |  10,00  |
 5    |   4,00     |  03/11/2010 |     A    |  11,00  |
 6    |   4,00     |  03/11/2010 |     A    |  12,00  |
 7    |   5,00     |  03/11/2010 |     A    |  13,00  |
 8    |   5,00     |  03/11/2010 |     A    |  14,00  |
 9    |   6,00     |  03/11/2010 |     A    |  15,00  |
10    |   7,00     |  03/11/2010 |     A    |  16,00  |
11    |   1,00     |  03/11/2010 |     B    |  17,00  |
12    |   2,50     |  03/11/2010 |     B    |  18,00  |
13    |   3,00     |  03/11/2010 |     B    |  19,00  |
14    |   3,00     |  03/11/2010 |     B    |  20,00  |
15    |   5,00     |  03/11/2010 |     B    |  21,00  |
16    |   6,00     |  03/11/2010 |     B    |  22,00  |
17    |   7,00     |  03/11/2010 |     B    |  23,00  |
18    |   7,00     |  03/11/2010 |     B    |  24,00  |

And I would like to build a table like this: 我想建立一个像这样的表:

 Price    |     Date    |   Size A |   Size B  |
-------------------------------------------------------
 1,00     |  01/11/2010 |    7,00  |   17,00   |
 2,50     |  02/11/2010 |    8,00  |           |
 2,50     |  03/11/2010 |    9,00  |   18,00   |
 3,00     |  02/11/2010 |   10,00  |   19,00   |
 4,00     |  03/11/2010 |   11,00  |           |
 4,00     |  04/11/2010 |   12,00  |           |
 5,00     |  03/11/2010 |   13,00  |   21,00   |
 5,00     |  04/11/2010 |   14,00  |           |
 6,00     |  05/11/2010 |   15,00  |           |
 7,00     |  06/11/2010 |   16,00  |   23,00   |

How can I do that in one query? 如何在一个查询中做到这一点?

Thanks for any help. 谢谢你的帮助。

select price, 
       date, 
       sum(case when `type` = 'A' then size else 0 end) as SizeA,
       sum(case when `type` = 'B' then size else 0 end) as SizeB
from products
group by price, date
order by price, date

Group by the date to get the data for each date. date分组以获取每个日期的数据。 To get the other columns you need to use aggregate functions like sum() . 要获取其他列,您需要使用诸如sum()类的聚合函数。

If you really need the null values you can do: 如果您确实需要null值,则可以执行以下操作:

case when sum(`type` = 'A') = 0 
     then null 
     else sum(case when `type` = 'A' then size end)
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM