0

I have a table INVENTORY which consists of inventory items. I have the following table structure:

INSTALLATION_ID
COMPONENT_ID
HISTORY_ID
ON_STOCK
LAST_CHANGE

I need to obtain the row with the max HISTORY ID for records for which the spcified LAST_CHANGE month doesn't exist.

Each COMPONENT_ID and INSTALLATION_ID can occur multiple times, they are distinguished by their respective HISTORY_ID

Example:

I have the following records

COMPONENT_ID | INSTALLATION_ID | HISTORY_ID | LAST_CHANGE

1 | 100 | 1 | 2013-01-02
1 | 100 | 2 | 2013-02-01
1 | 100 | 3 | 2013-04-09
2 | 100 | 1 | 2013-02-22
2 | 100 | 2 | 2013-03-12
2 | 100 | 3 | 2013-07-07
2 | 100 | 4 | 2013-08-11
2 | 100 | 5 | 2013-09-15
2 | 100 | 6 | 2013-09-29
3 | 100 | 1 | 2013-02-14
3 | 100 | 2 | 2013-09-23
4 | 100 | 1 | 2013-04-17

I am now trying to retrieve the rows with the max HISTORY ID for each component but ONLY for COMPONENT_IDs in which the specifiec month does not exists

I have tried the following:

SELECT 

INVENTORY.COMPONENT_ID,
INVENTORY.HISTORY_ID

FROM INVENTORY

WHERE INVENTORY.HISTORY_ID = (SELECT 
    MAX(t2.HISTORY_ID) 
    FROM INVENTORY t2
    WHERE NOT EXISTS 
    (
        SELECT *
        FROM INVENTORY t3
        WHERE MONTH(t3.LAST_CHANGE) = 9
        AND YEAR(t3.LAST_CHANGE)= 2013
        AND t3.HISTORY_ID = t2.HISTORY_ID
    )   
)

AND INVENTORY.INSTALLATION_ID = 200
AND YEAR(INVENTORY.LAST_CHANGE) = 2013

The query seems to have correct syntax but it times out.

In this particular case, i would like to retrieve the maximum HISTORY_ID for all components except for those that have records in September.

Because I need to completely exclude rows by their month, i cannot use NOT IN, since they will just suppress the records for september but the same component could show up with another month.

Could anybody give some pointers? Thanks a lot.

4

1 回答 1

1

如果我正确理解你想要什么,你可以这样做

SELECT component_id, MAX(history_id) history_id
  FROM inventory
 WHERE last_change BETWEEN '2013-01-01' AND '2013-12-31'
   AND installation_id = 100
 GROUP BY component_id
HAVING MAX(MONTH(last_change) = 9) = 0

输出:

| COMPONENT_ID | HISTORY_ID |
|---------------|------------|
| 1 | 3 |
| 4 | 1 |

如果您总是过滤installation_id一年,last_change请确保您有一个复合索引(installation_id, last_change)

ALTER TABLE inventory ADD INDEX (installation_id, last_change);

这是SQLFiddle演示

于 2013-10-11T15:05:27.070 回答