我们假设我们有图像表...
image_id
item_id
main - flag-field, saying that image_id is main image for item with item_id
是否可以在此表中插入行并确定飞行中的main
值?
如果item_id
没有任何图片,或items_id
= 1的main
没有任何图片,我们应该为插入的行设置main
= 1。否则main
= 0;
是否可以在单个SQL查询中生成?
谢谢。 PS:抱歉我的英文。 :)
答案 0 :(得分:1)
抱歉,没有。不在一个查询中。
您需要先在php应用程序中计算行数,然后根据该值设置main。
如果在数据库中执行此操作非常重要,您可以在触发器中执行此操作。
答案 1 :(得分:0)
尝试那样的smth ...现在输入存储在变量中的值,但它可以是简单的表...
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的例子......
最高
答案 2 :(得分:0)
如果你的表看起来像这样:
CREATE TABLE images (
image_id SERIAL,
item_id BIGINT UNSIGNED NOT NULL,
main TINYINT UNSIGNED NOT NULL,
path TINYTEXT NOT NULL
)
如果你想将图片'example.png'添加到商品 123 ,你可以使用:
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;