2011-08-09 57 views
0

讓我們假設我們有一個圖片表...插入一行取決於IF語句值(單個查詢)

image_id 
    item_id 
    main - flag-field, saying that image_id is main image for item with item_id 

是否有可能插入行此表,並確定飛main價值? 如果item_id沒有任何圖像,或者沒有任何圖像,main = 1 - 我們應該爲插入的行設置main = 1。否則main = 0;

是否可以在單個SQL查詢中創建?

謝謝。 PS:對不起,我的英文。 :)

回答

1

對不起,沒有。不在一個查詢中。

您將需要首先在您的php應用程序中對行進行計數,然後根據該值設置主。

你可以在觸發器中做到這一點,儘管它在數據庫中的確很重要。

+0

謝謝您的回答!所以,我想,我應該使用鎖定表來防止用main = 1模擬插入兩個圖像? MyISAM表可以嗎? – Kirzilla

+0

您不必鎖定整個表格,只需使用item_id的諮詢鎖定即可。像這樣:'SELECT GET_LOCK('image_ $ item_id',20)'。閱讀'GET_LOCK()'和'RELEASE_LOCK()'。確保檢查來自'GET_LOCK()'的返回值,以確保它沒有超時。 – Ariel

0

嘗試不服這樣...存儲在變量中現在輸入值,但它可以是簡單的表格......

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示例...

最大

0

如果您的表看起來財產以後這樣的:

CREATE TABLE images (
    image_id SERIAL, 
    item_id BIGINT UNSIGNED NOT NULL, 
    main TINYINT UNSIGNED NOT NULL, 
    path TINYTEXT NOT NULL 
) 

而且你要添加的圖片'example.png'項,你可以使用:

INSERT INTO images(item_id, main, path) 
SELECT new_image.item_id, IF(images.item_id IS NULL, 1, 0), new_image.path 
FROM (SELECT 123 as item_id, 'example.png' as path) AS new_image 
LEFT JOIN images USING (item_id) 
LIMIT 1;