开发者

Does MySQL use indexes on Having?

开发者 https://www.devze.com 2023-02-24 06:58 出处:网络
A portion of my query looks like: HAVING date > \'2011-04-13 04:28:03\' The date variable is indexed, does this have any effect on the query?

A portion of my query looks like:

HAVING date > '2011-04-13 04:28:03'

The date variable is indexed, does this have any effect on the query?

EXPLAIN EXTENDED doesn't seem to be using the index, but I don't know if that's only because I have 4 rows in the database that I'm testing with.

My query:

SELECT AVG(slen) FROM
(
SELECT date, COUNT(id) as slen
FROM table
WHERE product_id = 2830
GROUP BY id
HAVING date > '2011-04-13 04:28:02'
) as T

There are a few rows that have different date values. I want to select groups of ID that have a date > '2011-04-13 04:28:02'. I then want the average number of rows that belong to a group, without the date condition.

The query as it is, does not work yet by the way.

My other concern was whether the date > '2011-04-13 04:28:02' would use my date column index.

From this dataset:

sid             datelast                product_id
782240551706    2011-04-13 00:51:52     2830
782240551706    2011-04-13 04:05:48     2830
782240551706    2011-04-13 04:28:03     2830
111111111111    2011-04-13 00:50:30     2830

Desired Result:

The group with id 782240551706 should be chosen, and the 开发者_运维百科average should be 3.

The following query produces the desired result:

SELECT AVG(slen) FROM
(
SELECT date, COUNT(id) as slen
FROM table
WHERE product_id = 2830
GROUP BY id
HAVING **max(date)** > '2011-04-13 04:28:02'
) as T


HAVING is used in conjunction with a GROUP BY, so it's a derived table. I don't see how there would be an index to use.


For example:

SELECT 
    column1, 
    count(column2) as count 
FROM table 
GROUP BY column1 
HAVING count > 1

The count is calculated by your query. It's not indexed in your case. You can change the having clause to a where clause.


That query does not make sense, as the column "date" is in a GROUP BY, but is neither an aggregate nor GROUP BY clause.

Any normal SQL database would reject it; mysql would reject it if in strict mode.

The behaviour is basically undefined in this case. Don't do it.

I'm pretty sure you want WHERE to filter your rows, not HAVING. And you don't want to specify date in the column list, try min(date) or max(date) instead.

And no, HAVING won't use an index because it needs to perform the GROUP BY to find the groups which HAVING matches. Normally it is better to use WHERE, and you'd only use HAVING on an aggregate (e.g. HAVING COUNT(*) > 1)

0

精彩评论

暂无评论...
验证码 换一张
取 消