mysql - 加入 2 个表以产生所需的输出

标签 mysql sql

我有如下 2 个表:

产品表:

ProductID   Name
   1        Condensed cheese
   2        Milk       

价格表:

ProductID   Currency   Price
    2          EUR       1.50
    2          USD       1.74
    2          JPY     194.624
    1          EUR       0.99
    1          USD       1.15

我正在学习 SQL 并想知道连接上面的 2 个表以产生此输出的 SQL 语句是什么:

ProductID     Name               EUR     USD     JPY
    1         Condensed cheese   0.99    1.15    NULL
    2         Milk               1.50    1.74    194.624

最佳答案

你可以使用 max() 函数来区分大小写

select t1.ProductID ,t1.Name,
 max(case when t2.Currenc= 'EUR' then Price end) as EUR,
 max(case when t2.Currenc= 'USD' then Price end) as USD,
 max(case when t2.Currenc= 'JPY' then Price end) as JPY
 from 
Products t1 join Prices  t2 on t1.ProductID =t2.ProductID  
group by t1.ProductID ,t1.Name   

关于mysql - 加入 2 个表以产生所需的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52795928/

相关文章:

SQL LIKE 语句适用于特定字符之前的所有内容

MySQL - 如何选择最小/最大日期差异超过 3 年的 id

sql - 在 SQL 中保留文本格式

mysql HOUR() 占时区

mysql - 如何让MySQL程序检测错误

php - 从 mysql 中选择其中 2 个单元是相同的

mysql - mysql中按列名和数字分组的定义行为是什么

sql - 替换交替出现的子字符串

php mysql 批量或批量更新多列和多行,但如果列不为空则不更新

php - 在文章索引中计算文章评论、点击和喜欢的正确方法是什么?