简体   繁体   English

使用单个查询更新SQL

[英]Sql update with single query

This question is asked by my friend. 我的朋友问了这个问题。 He faced this question during an interview. 他在一次采访中面临这个问题。 Please forget about db structure :), I think they asked this question to check logic :) 请忘记数据库结构:),我认为他们问了这个问题以检查逻辑:)

Here is the scenario. 这是场景。 There is a hotel with different floors and different room numbers in each room. 旅馆的楼层不同,每个房间的房间号也不同。

Initially table will be like this; 最初的表格将是这样;

Floor Rooms
1
1
1
2
2

Rooms column will have null values “房间”列的值为空

We need to fill as shown below using a single query. 我们需要使用单个查询来填充,如下所示。 Is this possible? 这可能吗? If so how we can do that. 如果是这样,我们该怎么做。 Please advice. 请指教。

Floor    Rooms
1        101
1        102  
1        103
2        201
2        202

Very simple,Code for SQL Server, 非常简单,SQL Server代码,

with cte as
(
select * 
,ROW_NUMBER() over (partition by  fno order by fno) as rowNo
 from hotel
 )
 update cte set rNo = fno*100 + rowNo

DEMO DEMO

Code of MySQL, I was able to select only, for update Temp table should be used, I am new to MYSQL. MySQL代码,我只能选择,应该使用更新的Temp表,我是MYSQL的新手。

set @type = 1;
set @num  = 0;

select fno,(fno*100) + row_number as newRommNo  from
(
select * 
,@num := if(@type = fno, @num + 1, 1) as row_number
,@type :=fno
 from hotel
) as a

DEMO OF MYSQL MySQL的演示

试试这个

update tablename set `Rooms`=(Floor*100)+1

This is may be help for you 这可能对您有帮助

we must declare scalar variable: 我们必须声明scalar变量:

SELECT fno, CASE WHEN fno = 1 THEN fno * 100 +@rooms :=@rooms + 1 
WHEN fno = 2 THEN fno * 100 +@room :=@room + 1 END FROM hotel, 
(SELECT @rooms := 0) AS w1, (SELECT @room := 0) AS w2

here demo : http://sqlfiddle.com/#!2/54c0d/1 此处演示: http : //sqlfiddle.com/#!2/54c0d/1

Use this query if you're looking for a true atomic solution without having to set and reset session variables outside of your update query: 如果您要寻找真正的原子解决方案,而不必在更新查询之外设置和重置会话变量,请使用此查询:

UPDATE floor_rooms
    INNER JOIN (
        SELECT DISTINCT floor, (@room := 0), (@floor := 0)
            FROM floor_rooms
            WHERE ISNULL(room)
    ) AS floors
    ON floor_rooms.floor = floors.floor
    SET floor_rooms.room =
        IF(@floor = floor_rooms.floor, @room := (@room + 1), @room := 1)
        + (@floor := floor_rooms.floor) * 100;

DEMO @ SQL Fiddle DEMO @ SQL小提琴

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

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