我有一个像这样的mysql表:
##############################################
# ID # TAG 1 # TAG 2 # TAG 3 # TAG 4 # TAG 5 #
#--------------------------------------------#
# 1 # A # B # C # D # E #
# 2 # B # G # H # J # K #
##############################################
让我们说我需要选择价值为" B"的所有标签。并使它成为""。
问题:这样做的查询是什么?
由于
答案 0 :(得分:2)
几个问题:
UPDATE yourTable SET TAG1 = '' WHERE TAG1 = 'B';
UPDATE yourTable SET TAG2 = '' WHERE TAG2 = 'B';
UPDATE yourTable SET TAG3 = '' WHERE TAG3 = 'B';
UPDATE yourTable SET TAG4 = '' WHERE TAG4 = 'B';
UPDATE yourTable SET TAG5 = '' WHERE TAG5 = 'B';
一个查询:
UPDATE yourTable SET
TAG1 = CASE WHEN TAG1 = 'B' THEN '' ELSE TAG1 END,
TAG2 = CASE WHEN TAG2 = 'B' THEN '' ELSE TAG2 END,
TAG3 = CASE WHEN TAG3 = 'B' THEN '' ELSE TAG3 END,
TAG4 = CASE WHEN TAG4 = 'B' THEN '' ELSE TAG4 END,
TAG5 = CASE WHEN TAG5 = 'B' THEN '' ELSE TAG5 END
-- the where clause is optional, but prevents updating every row
WHERE TAG1 = 'B' OR TAG2 = 'B' OR TAG3 = 'B' OR TAG4 = 'B' OR TAG5 = 'B'
没有什么是最佳的,但两种方式都应该有效。
从更一般的角度来看,考虑构建一个包含id和其他相关数据的表(我猜id指的是某些东西)并构建一个引用它的标记表:
<强> mainTable 强>
id | other
----------
1 | foo
2 | bar
<强>代码
id | pos | val
--------------
1 | 1 | A
1 | 2 | B
1 | 3 | C
1 | 4 | D
1 | 5 | E
2 | 1 | B
2 | 2 | G
2 | 3 | H
2 | 4 | J
2 | 5 | K
通过这种方式,您可以使用标准化模型,并可以使用以下方法实现您的要求:
UPDATE tags SET val = '' WHERE val = 'B'
答案 1 :(得分:0)
UPDATE myTable
SET `TAG 1` = IF(`TAG 1` = 'B', '', `TAG 1`),
`TAG 2` = IF(`TAG 2` = 'B', '', `TAG 2`),
`TAG 3` = IF(`TAG 3` = 'B', '', `TAG 3`),
`TAG 4` = IF(`TAG 4` = 'B', '', `TAG 4`),
`TAG 5` = IF(`TAG 5` = 'B', '', `TAG 5`);
答案 2 :(得分:0)
您可以对您的案例使用此查询(SELECT WITH CASE WHEN):
SELECT ID,
CASE TAG_1
WHEN 'B' THEN ''
ELSE TAG_1
END as TAG_1,
CASE TAG_2
WHEN 'B' THEN ''
ELSE TAG_2
END as TAG_2,
CASE TAG_3
WHEN 'B' THEN ''
ELSE TAG_3
END as TAG_3,
CASE TAG_4
WHEN 'B' THEN ''
ELSE TAG_4
END as TAG_4,
CASE TAG_5
WHEN 'B' THEN ''
ELSE TAG_5
END as TAG_5
FROM table;
或更新IF Clause:
UPDATE table
SET TAG_1 = IF(TAG_1 = 'B', '', TAG_1),
TAG_2 = IF(TAG_2 = 'B', '', TAG_2),
TAG_3 = IF(TAG_3 = 'B', '', TAG_3),
TAG_4 = IF(TAG_4 = 'B', '', TAG_4),
TAG_5 = IF(TAG_5 = 'B', '', TAG_5);