嘗試不服這樣...存儲在變量中現在輸入值,但它可以是簡單的表格......
create table #T (image_id int, item_id int, main int)
declare @new_image_id int, @new_item_id int
insert #T values (0,1,0)
insert #T values (0,1,0)
insert #T values (0,1,0)
insert #T values (0,2,0)
insert #T values (1,2,0)
insert #T values (1,2,0)
/*first example - no any images for item_id*/
select @new_image_id = 123, @new_item_id = 1
insert #T
select @new_image_id, @new_item_id,
CASE
WHEN NOT EXISTS (select 1 from #T where item_id = @new_item_id and @new_image_id != 0)
THEN 1
WHEN NOT EXISTS (select 1 from #T where item_id = @new_item_id and main = 1)
THEN 1
ELSE 0
END
/*second example - no any images for items_id with main=1*/
select @new_image_id = 234, @new_item_id = 2
insert #T
select @new_image_id, @new_item_id,
CASE
WHEN NOT EXISTS (select 1 from #T where item_id = @new_item_id and @new_image_id != 0)
THEN 1
WHEN NOT EXISTS (select 1 from #T where item_id = @new_item_id and main = 1)
THEN 1
ELSE 0
END
/*third example - new record with main = 0*/
select @new_image_id = 435, @new_item_id = 2
insert #T
select @new_image_id, @new_item_id,
CASE
WHEN NOT EXISTS (select 1 from #T where item_id = @new_item_id and @new_image_id != 0)
THEN 1
WHEN NOT EXISTS (select 1 from #T where item_id = @new_item_id and main = 1)
THEN 1
ELSE 0
END
select * from #T
上T-SQL示例...
最大
來源
2011-08-09 11:05:03
Max
謝謝您的回答!所以,我想,我應該使用鎖定表來防止用main = 1模擬插入兩個圖像? MyISAM表可以嗎? – Kirzilla
您不必鎖定整個表格,只需使用item_id的諮詢鎖定即可。像這樣:'SELECT GET_LOCK('image_ $ item_id',20)'。閱讀'GET_LOCK()'和'RELEASE_LOCK()'。確保檢查來自'GET_LOCK()'的返回值,以確保它沒有超時。 – Ariel