力扣数据库题库学习(5.8日)--1795. 每个产品在不同商店的价格

1795. 每个产品在不同商店的价格

复制代码
请你重构 Products 表,查询每个产品在不同商店的价格,使得输出的格式变为(product_id, store, price) 。如果这一产品在商店里没有出售,则不输出这一行。
输出结果表中的 顺序不作要求 。
查询输出格式请参考下面示例。

示例 1:

输入:
Products table:
+------------+--------+--------+--------+
| product_id | store1 | store2 | store3 |
+------------+--------+--------+--------+
| 0          | 95     | 100    | 105    |
| 1          | 70     | null   | 80     |
+------------+--------+--------+--------+
输出:
+------------+--------+-------+
| product_id | store  | price |
+------------+--------+-------+
| 0          | store1 | 95    |
| 0          | store2 | 100   |
| 0          | store3 | 105   |
| 1          | store1 | 70    |
| 1          | store3 | 80    |
+------------+--------+-------+
解释:
产品 0 在 store1、store2、store3 的价格分别为 95、100、105。
产品 1 在 store1、store3 的价格分别为 70、80。在 store2 无法买到。

思路分析

要求我们重构输出:

  1. 将旧表除了product_id的其他字段名作为新表store字段值
  2. 将旧表除了product_id的其他字段值,作为新表price字段值

这个表内就只有三个其他字段,我们可以直接暴力筛选store1、store2、store3的值作为price,然后将结果使用UNION ALL合并起来即可。

暴力的代码如下:

复制代码
SELECT product_id, 'store1' AS store, store1 AS price FROM Products WHERE store1 IS NOT NULL
UNION ALL
SELECT product_id, 'store2' AS store, store2 AS price FROM Products WHERE store2 IS NOT NULL
UNION ALL
SELECT product_id, 'store3' AS store, store3 AS price FROM Products WHERE store3 IS NOT NULL;
相关推荐
LGL6030A27 分钟前
Java学习历程31——初识Spring Boot
java·spring boot·学习
xiaoye-duck32 分钟前
《C++ 项目:手写大模型接入 SDK》会话模块整合:内存 SessionManager 与 DataManager 持久化联动
开发语言·数据库·c++·语言模型
AllData公司负责人1 小时前
AI大模型数据开发底座系列说明书:AllData集成DB-GPT开源项目建设 AI 多模态分析底座,涵盖模态解析/智能大屏/MCP 扩展!
大数据·数据库·人工智能·gpt·数据采集·数据接入·模态解析
隔窗听雨眠1 小时前
MySQL进程卡死的定位思路与恢复实践
mysql·故障排查·数据库运维
2601_967987372 小时前
Sqlite参考手册
数据库·python·sqlite·api·教程
阿达和自己2 小时前
springboot学习-springboot引入MyBatis-Plus
spring boot·学习·mybatis
隔窗听雨眠2 小时前
Oracle日志体系分层结构与故障定位路径
数据库·oracle·故障排查
为思念酝酿的痛2 小时前
C语言操作MySQL
数据库·mysql
旖旎夜光2 小时前
【C++ 基础入门】C++11 新特性(中):右值引用、移动语义与完美转发
开发语言·c++·笔记·学习
ShineWinsu3 小时前
对于Qt:QTabWidget常见属性的解析
开发语言·数据库·c++·qt·浏览器·qtabwidget·标签页