[英]MySQL COUNT() not returning total number it is counting each rows separately
I am having some problem with my MySQL query and I need some guidance here.我的 MySQL 查询有问题,我需要一些指导。 I am creating a search and I want to know how many item was found in my search with my query.
我正在创建一个搜索,我想知道我的查询在我的搜索中找到了多少项目。 But the problem is, my query returning count for each rows separately, It's not returning total count.
但问题是,我的查询分别返回每行的计数,它没有返回总计数。 Here what I have right now.
这是我现在所拥有的。
My query我的查询
SELECT
COUNT(t.id) AS total
FROM
trouble t
LEFT JOIN district d ON d.id = t.district
LEFT JOIN country c ON c.id = t.country
LEFT JOIN multi_category mc ON mc.t_id = t.id
LEFT JOIN category ct ON ct.id = mc.ct_id
LEFT JOIN state s ON s.id = t.state
WHERE
t.name LIKE '%keyword%' OR
t.title LIKE '%keyword%' OR
t.tags LIKE '%keyword%' OR
ct.category LIKE '%keyword%' OR
c.country LIKE '%keyword%' OR
s.state LIKE '%keyword%' OR
d.district LIKE '%keyword%'
GROUP BY
t.id
I have 14 rows in my database with the keyword I am searching with and this query returning 14 rows, here is a snap.我的数据库中有 14 行带有我正在搜索的关键字,这个查询返回 14 行,这是一个快照。
But it is counting each rows id's individually.但它是单独计算每一行 id 的。 I don't want that.
我不想要那个。 What I want is, I want the total row count which is 14 and I want it in a single row.
我想要的是,我想要总行数为 14,并且我想要它在一行中。 Can you please help me achieve this?
你能帮我实现这个吗?
Thanks in advance.提前致谢。
First get the unique number of IDs and then return the total number of IDs.首先获取 ID 的唯一数量,然后返回 ID 的总数。
SELECT count(*) AS Total
FROM
(
SELECT DISTINCT t.id
FROM trouble t
LEFT JOIN district d ON d.id = t.district
LEFT JOIN country c ON c.id = t.country
LEFT JOIN multi_category mc ON mc.t_id = t.id
LEFT JOIN category ct ON ct.id = mc.ct_id
LEFT JOIN state s ON s.id = t.state
WHERE
t.name LIKE '%keyword%' OR
t.title LIKE '%keyword%' OR
t.tags LIKE '%keyword%' OR
ct.category LIKE '%keyword%' OR
c.country LIKE '%keyword%' OR
s.state LIKE '%keyword%' OR
d.district LIKE '%keyword%'
GROUP BY t.id
) resultTable
Use exists
instead of LEFT JOIN
s.使用
exists
而不是LEFT JOIN
s。 The joins just multiply rows when there are multiple matches:当有多个匹配项时,连接只会增加行:
SELECT COUNT(*)
FROM trouble t
WHERE t.name LIKE '%keyword%' OR
t.title LIKE '%keyword%' OR
t.tags LIKE '%keyword%' OR
EXISTS (SELECT 1
FROM district d
WHERE d.id = t.district AND d.district LIKE '%keyword%'
) OR
EXISTS (SELECT 1
FROM country c
WHERE c.id = t.country AND c.country LIKE '%keyword%'
) OR
EXISTS (SELECT 1
FROM state s
WHERE s.id = t.state AND s.state LIKE '%keyword%'
) OR
EXISTS (SELECT 1
FROM multi_category mc JOIN
category ct
ON ct.id = mc.ct_id
WHERE mc.t_id = t.id AND
(ct.category LIKE '%keyword%' OR
c.country LIKE '%keyword%'
)
);
By eliminating the creation of multiple rows, this should also be faster.通过消除多行的创建,这也应该更快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.