我正在尝试计算一个单词出现在一行的所有列中的次数,这是一个id。
+-------+------+------+------+------+------+------+
| id | pos1 | pos2 | pos3 | pos4 | pos5 | pos6 |
+-------+------+------+------+------+------+------+
| core1 | AA | BB | CC | HH | YY | var1 |
| core2 | AA | BB | var3 | TT | var2 | YY |
| core5 | AA | BB | EE | GG | YY | ZZ |
+-------+------+------+------+------+------+------+
我已尝试使用此代码但仅返回' 1'而不是' 2'这就是我想要的。
SELECT count(id) FROM customize WHERE pos1 OR pos2 OR pos3 OR pos4 OR pos5 OR pos6 LIKE 'var%' AND id = 'core2';
我怎么能这样做?
答案 0 :(得分:0)
SELECT
(IF(pos1 LIKE 'var%', 1, 0) +
IF(pos2 LIKE 'var%', 1, 0) +
IF(pos3 LIKE 'var%', 1, 0) +
IF(pos4 LIKE 'var%', 1, 0) +
IF(pos5 LIKE 'var%', 1, 0) +
IF(pos6 LIKE 'var%', 1, 0)) AS done
FROM customize
WHERE id = 'core2'
答案 1 :(得分:-1)
可能会加载一个联合查询(每列一个),然后计算结果。
SELECT COUNT(*)
FROM
(
SELECT id
FROM customize
WHERE id = 'core2'
AND pos1 LIKE 'var%'
UNION ALL
SELECT id
FROM customize
WHERE id = 'core2'
AND pos2 LIKE 'var%'
UNION ALL
SELECT id
FROM customize
WHERE id = 'core2'
AND pos3 LIKE 'var%'
UNION ALL
SELECT id
FROM customize
WHERE id = 'core2'
AND pos4 LIKE 'var%'
UNION ALL
SELECT id
FROM customize
WHERE id = 'core2'
AND pos5 LIKE 'var%'
UNION ALL
SELECT id
FROM customize
WHERE id = 'core2'
AND pos6 LIKE 'var%'
)
或者,如果您希望计算具有该值的列的行: -
SELECT COUNT(id)
FROM customize
WHERE id = 'core2'
AND (pos1 LIKE 'var%' OR pos2 LIKE 'var%' OR pos3 LIKE 'var%' OR pos4 LIKE 'var%' OR pos5 LIKE 'var%' OR pos6 LIKE 'var%')
但更好地规范化您的数据库设计
答案 2 :(得分:-1)
我想你可能想要更像这样的东西:
select
IF(Pos1 LIKE 'var%', 1, 0) +
IF(Pos2 LIKE 'var%', 1, 0) +
IF(Pos3 LIKE 'var%', 1, 0) +
IF(Pos4 LIKE 'var%', 1, 0) +
IF(Pos5 LIKE 'var%', 1, 0) +
IF(Pos6 LIKE 'var%', 1, 0)
FROM customize
where id = 'core2'
答案 3 :(得分:-1)
尝试从概念上分解问题总是有帮助的。解决这个问题有两个阶段。第一种是转动输入表,将列转换为行。
第二种是计算字符串的值。
这是两个查询(http://sqlfiddle.com/#!2/3731e/7/0)。
SELECT COUNT(*) AS stringcount, pos AS string
FROM ( -- pivot the original table
SELECT id, 1 AS i, pos1 AS Pos FROM customize
UNION ALL SELECT id, 2 AS i, pos2 AS Pos FROM customize
UNION ALL SELECT id, 3 AS i, pos3 AS Pos FROM customize
UNION ALL SELECT id, 4 AS i, pos4 AS Pos FROM customize
UNION ALL SELECT id, 5 AS i, pos5 AS Pos FROM customize
UNION ALL SELECT id, 6 AS i, pos6 AS Pos FROM customize
) AS pivoted
GROUP BY pos
ORDER BY COUNT(*) DESC, pos