题1.
请你编写一个解决方案来交换所有的 'f'
和 'm'
(即,将所有 'f'
变为 'm'
,反之亦然),仅使用 单个 update 语句 ,且不产生中间临时表。
注意,你必须仅使用一条 update 语句,且 不能 使用 select 语句。
记录.
update Salary
set sex=case when sex="m" then "f"
when sex="f" then "m"
end
主要复习一下update的有关基本语法结构:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
- table_name 是要更新数据的表名。
- column1 = value1, column2 = value2, ... 指定了要更新的列和它们的新值。
- WHERE condition 是可选的,用于指定更新的条件。如果省略 WHERE 子句,将更新表中的所有行。
题2.
请你重构 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 | +------------+--------+-------+
记录.
select * from(
select product_id,"store1" as store,store1 as price from Products
union
select product_id,"store2" as store,store2 as price from Products
union
select product_id,"store3" as store,store3 as price from Products
) a
where price is not null
此处主要记录表重构中经常使用的添加常量列操作,即其中的
select 表变量,“常量” as 常量列名 from 表名;