使用where子句在三个不同的列上使用count

时间:2014-02-01 09:08:15

标签: mysql sql select

我正在尝试计数 sub_tag_1,sub_tag_2,sub_tag_3列仅当其中条件为真且最后我想要总和时结果三列。

这是我的虚拟表:

+---+-----------+-----------+-----------+
| id| sub_tag_1 | sub_tag_2 | sub_tag_3 |
+---+-----------+-----------+-----------+
| 1 |   php     |           |           |
| 2 |   mysql   |     php   |           |
| 3 |   java    |           |     php   |
+---+-----------+---------+-------------+

我已经尝试了很多次,但我每次都失败了,这里是我的SQL查询:

1) SELECT count(`sub_tag_1`) AND count(`sub_tag_2`) AND count(`sub_tag_3`) 
FROM posts where `sub_tag_1` 
LIKE "php" and `sub_tag_2` LIKE "php" and `sub_tag_3` LIKE "php";

以上查询执行成功,但它与数据库中的任何内容都不匹配,并且返回0

2) SELECT count(`sub_tag_1`) AND count(`sub_tag_2`) AND count(`sub_tag_3`) 
FROM posts where `sub_tag_1` = "php" and `sub_tag_2` = "php" 
and `sub_tag_3` = "php" 
and sum(count(`sub_tag_1`)+count(`sub_tag_2`)+count(`sub_tag_3`));

以上查询给我错误:无效使用群组功能

请逐步建议和解释我该怎么做..

1 个答案:

答案 0 :(得分:1)

WHERE子句中添加一个confition将为您提供所有三列中php的所有行。由于没有,您将获得结果0

您要做的是检索所有行并仅计算适当的值。这可以通过对每列使用CASE子句来完成,方式如下:

SELECT SUM(CASE sub_tag_1 WHEN 'php' THEN 1 ELSE 0 END) AS subg_tag_1_count, 
       SUM(CASE sub_tag_2 WHEN 'php' THEN 1 ELSE 0 END) AS subg_tag_2_count, 
       SUM(CASE sub_tag_3 WHEN 'php' THEN 1 ELSE 0 END) AS subg_tag_3_count
FROM   my_table
WHERE  'php' IN (sub_tag_1, sub_tag_2, sub_tag_3)