如果值存在,请更新

时间:2012-11-21 16:34:25

标签: mysql

好的,我有一张桌子,我将收集用户设备。当用户登录时,我希望它注册设备,如果它已经存在,它只想更新时间戳。这仅在用户登录时才会显示。

表格如下:

device_id => BIGINT AUTOINCREMENT PRIMARY KEY
user_id => BIGINT FOREIGN KEY users(id)
device_name => VARCHAR(40) (Will be like 'Donald ducks iphone')
device_type => VARCHAR(10) (Will be defined by the client, like "IOS")
last_usage => TIMESTAMP (On update, new timestamp and all that)

因此,当用户登录时,我有user_id,device_name,device_type。

我想要的: 如果id,name和type已经存在于一行中,只需更新时间戳,否则插入值。

由于这与主键无关,我不知道如何做到这一点。当然我可以做一些事情,比如先选择这些值,然后返回并在之后进行更新/插入,但这感觉不对:)

4 个答案:

答案 0 :(得分:3)

您可以在MySQL 5.0 +中使用REPLACE

  

REPLACE的工作原理与INSERT完全相同,只是如果在一个旧行中   table与PRIMARY KEY或UNIQUE的新行具有相同的值   index,在插入新行之前删除旧行

示例:

REPLACE INTO TableName (user_id, device_id, device_name, device_type, last_usage) VAULES (1, 2, "Test Device Name, "Test Type", NOW()); 

答案 1 :(得分:3)

首先,将device_namedevice_type设为唯一。

现在你有几个选择。您可以使用:

INSERT IGNORE INTO devices (...) VALUES(...)

或者如果您担心重要错误可能会被忽略,请使用:

INSERT INTO devices (...) VALUES(...)
ON DUPLICATE KEY UPDATE device_id = device_id

请注意,这与REPLACE不同,因为这根本不会影响旧记录,而REPLACE会创建新的ID和时间戳。

编辑:由于您现在想要更新时间戳,请使用:

INSERT INTO devices (...) VALUES(...)
ON DUPLICATE KEY UPDATE last_usage = NOW()

答案 2 :(得分:0)

For Each r In Me.Lstbox_Tables.ItemsSelected

'Create a recordset with required data

sql = "SELECT * FROM " & Me.Lstbox_Tables.ItemData(r)

'tablename = "Gahpp00d_" + rs!Table_Name

Set rs = db.OpenRecordset(sql, dbReadOnly)

Dim SheetName As String

SheetName = Replace(Me.Lstbox_Tables.ItemData(r), "GAHPP00D_", "")


On Error Resume Next

excelWbk.Sheets(SheetName).Select

If Err.Number <> 0 Then

MsgBox Err.Number & ":" & Err.Description, vbCritical, "ERROR!!!"

MsgBox "Worksheet " & SheetName & " doesn't exist.", vbCritical, "Sheet Missing!!!"

excelWbk.Close False

appExcel.Quit


 Exit Sub

 End If

答案 3 :(得分:0)

您可能需要将其转换为mysql作为其mssql,但有些内容如下:

declare @count int
declare @user varchar
declare @machine varchar
declare @type as varchar

select @count = (select count(*) from [table] where user = @user and machine=@machine and type=@type)

if @count = 0
begin
insert into
[table]
select
@machine,
@user,
@type,
current_timestamp
end

if @count > 0
begin
update
[table]
set timestamp = current_timestamp
where
machine = @machine
and
user = @user
and
type = @type
end

此致

马库斯