了解各种条件

时间:2016-05-04 16:42:08

标签: php mysql

我正在向SQL查询解析mysqli命令。我想得到不同条件的记录数。我目前使用union执行此操作,但速度非常慢。有没有更好的更有效的方法呢?

$sql  = "SELECT COUNT(*) as Total FROM table1 WHERE GroupId = 2 UNION ";
$sql .= "SELECT COUNT(*) as Likes FROM table1 WHERE LikesCol IS NOT NULL AND GroupId = 2 UNION ";
$sql .= "SELECT COUNT(*) as Commented FROM table1 WHERE CommentCol > 0 AND GroupId = 2 UNION ";
$sql .= "SELECT COUNT(*) as Shared FROM table1 WHERE SharedCol > 0 AND GroupId = 2";

正如您将注意到我正在从GroupId = 2表格中选择所有记录,然后我将深入了解谁共享和评论等。

1 个答案:

答案 0 :(得分:2)

SELECT sum(GroupId = 2) as Total,
       sum(LikesCol IS NOT NULL AND GroupId = 2) as Likes,
       sum(CommentCol > 0 AND GroupId = 2) as Commented,
       sum(SharedCol > 0 AND GroupId = 2) as Shared
FROM table1
感谢Paul的一丝暗示,甚至更好。

SELECT count(*) as Total,
       sum(LikesCol IS NOT NULL) as Likes,
       sum(CommentCol > 0) as Commented,
       sum(SharedCol > 0) as Shared
FROM table1
WHERE GroupId = 2