【发布时间】:2013-10-17 18:24:43
【问题描述】:
我正在四处寻找,但无法破译人们试图做的场景并适应我的场景。
有一个stackoverflow q&a 与我的问题很接近,但答案很奇怪,我不知道答案中的破折号是否应该存在。另外,我不确定问号之前和之后的名称是如何工作的,以及我的场景中的哪些名称应该放在问号之前或之后的位置。
所以我需要在提交表单时更新 2 个字段。如果 2 个字段有数据,则不要使用这 2 个字段,使用另外 2 个字段,但如果其他 2 个字段已填写,则使用第三组 2 个字段,依此类推。
我知道这是一种不好的技术,我应该进行标准化,但这只是一个简单的应用程序,最多可能有 2 人尝试同时提交所述表单,发生这种情况的可能性是 100,000到 1,但我仍然想防止它发生。
我的桌子是这样的:
表名是工作,这些是字段
id
name
path
jobid
note1
note1user
note2
note2user
note3
note3user
note4
note4user
note5
note5user
note6
note6user
所以如果 note1 和 note1user 不为 null 或为空,请使用 note2 和 note2user。 如果 note2 和 note2user 不为 null 或为空,请使用 note3 和 note3user。 等等。 如果 note6 和 note6user 有数据,那没关系,因为提交时不会显示表单。
我在其他地方看到的代码是这样的,但不知道如何适应我的场景:
update table_name set
col1 = ( case when col1 is null then ? else col1 end )
, col2 = ( case when col2 is null then ? else col2 end )
-- , col3 = ...
;
我会试着猜一猜。以下代码块看起来如何?我取下了那些破折号,因为我不喜欢它在那里的样子。甚至不确定是否需要分号。最后一个想法是,这是一次一个领域的场景。我如何一次处理 2 个字段?换句话说,我如何通过note6user合并note1user?
update jobs set
note1 = ( case when note1 is null then ? else note1 end ),
note2 = ( case when note2 is null then ? else note2 end ),
note3 = ( case when note3 is null then ? else note3 end ),
note4 = ( case when note4 is null then ? else note4 end ),
note5 = ( case when note5 is null then ? else note5 end )
感谢您提供任何提示和技巧以及 sn-ps。
更新
这是给巴尔玛的。
这不会产生错误,但不会将任何内容写入数据库。不要担心它说更新文件。那是我要写的表。当我说这是工作时,我搞砸了我的问题。此外,无论我将所有笔记放在一起并将笔记用户放在一起,或者我将每个笔记放在一起,以下内容都是相同的。
UPDATE files SET
note_6 = (CASE WHEN note_6 IS NULL AND note_5 IS NOT NULL THEN '$note_6' ELSE note_6 END),
note_6_user = (CASE WHEN note_6_user IS NULL AND note_5_user IS NOT NULL THEN '$note_6_user' ELSE note_6_user END),
note_5 = (CASE WHEN note_5 IS NULL AND note_4 IS NOT NULL THEN '$note_5' ELSE note_5 END),
note_5_user = (CASE WHEN note_5_user IS NULL AND note_4_user IS NOT NULL THEN '$note_5_user' ELSE note_5_user END),
note_4 = (CASE WHEN note_4 IS NULL AND note_3 IS NOT NULL THEN '$note_4' ELSE note_4 END),
note_4_user = (CASE WHEN note_4_user IS NULL AND note_3_user IS NOT NULL THEN '$note_4_user' ELSE note_4_user END),
note_3 = (CASE WHEN note_3 IS NULL AND note_2 IS NOT NULL THEN '$note_3' ELSE note_3 END),
note_3_user = (CASE WHEN note_3_user IS NULL AND note_2_user IS NOT NULL THEN '$note_3_user' ELSE note_3_user END),
note_2 = (CASE WHEN note_2 IS NULL AND note_1 IS NOT NULL THEN '$note_2' ELSE note_2 END),
note_2_user = (CASE WHEN note_2_user IS NULL AND note_1_user IS NOT NULL THEN '$note_2_user' ELSE note_2_user END),
note_1 = (CASE WHEN note_1 IS NULL THEN '$note_1' ELSE note_1 END),
note_1_user = (CASE WHEN note_1_user IS NULL THEN '$note_1_user' ELSE note_1_user END)
WHERE id='$id'
更新
允许它工作的最后一件事是使数据库中的字段具有默认值 NULL。我无法让它与 empty 一起使用。
【问题讨论】:
-
你明白破折号在 SQL 中表示 cmets,对吧?
-
该代码的基本问题是它将更新所有非空字段,而不仅仅是第一个。我不认为那是你想要的,是吗?
-
能否附上另一个问题的链接?
-
不,一次只能写入 2 个字段。