我正在向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
表格中选择所有记录,然后我将深入了解谁共享和评论等。
答案 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