TransactionHistory Table:
CREATE TABLE `TransactionHistory` (
`id` varchar(200) NOT NULL,
`transactionType` varchar(200) DEFAULT NULL,
`startDate` bigint(20) DEFAULT NULL,
`completionDate` bigint(20) DEFAULT NULL,
`userId` varchar(200) DEFAULT NULL,
`status` varchar(200) DEFAULT NULL,
`error_code` varchar(200) DEFAULT NULL,
`transactioNumber` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `transactioNumber_index` (`transactioNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
User Table:
CREATE TABLE `User` (
`userId` varchar(200) NOT NULL,
`name` varchar(200) DEFAULT NULL,
PRIMARY KEY (`userId`),
KEY `userId_index` (`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Scenario:
- Group TransactionHistory by transactioNumber
- If groupSize == 1,
- display value in transactionType, startDate, completionDate, status, error_code
- If groupSize > 1
- display '' for transactionType
- display MIN startdate, and MAX startdate
- for STATUS and ERROR_CODE
- display status = SUCCESS, error_code = '0' if all status in group = SUCCESS,
- display status = FAILED, error_code = '99' if all status in group = FAILED,
- display status = WARNING, error_code = '-1' if mixed
- Display name of userName (if transaction has userId)
- If groupSize == 1,
I came up with this query:
SELECT tx.id,
CASE WHEN COUNT(*) = 1 THEN transactionType ELSE '' END as transactionType,
CASE WHEN COUNT(*) = 1 THEN status ELSE (
CASE WHEN COUNT(CASE WHEN STATUS = 'SUCCESS' THEN 1 END) = 0 THEN 'FAILED'
WHEN COUNT(CASE WHEN STATUS = 'FAILED' THEN 1 END) = 0 THEN 'SUCCESS'
ELSE 'WARNING' END) END as status,
CASE WHEN COUNT(*) = 1 THEN error_code ELSE (
CASE WHEN COUNT(CASE WHEN STATUS = 'SUCCESS' THEN 1 END) = 0 THEN '99'
WHEN COUNT(CASE WHEN STATUS = 'FAILED' THEN 1 END) = 0 THEN '0'
ELSE '-1' END) END as status
MAX(completionDate) as completionDate,
MIN(startDate) as startDate,
a.userId, a.name,
transactioNumber
FROM TransactionHistory tx LEFT JOIN User a ON tx.userId = a.userId
GROUP BY transactioNumber
LIMIT 0, 20 //pagination
However if I need to add filtering, the query takes too long to complete. I read it will be faster to put WHERE filter before GROUP BY instead of HAVING, but I cannot filter status and error_code correctly as WARNING and -1 values are only present after GROUP BY
HAVING STATUS = 'WARNING'
Also if I need to count the total number of grouped entries, it takes too long.
My EXPLAIN shows the following
select_type: SIMPLE
table: tx
type: ALL
possible_keys: NULL
key_len: NULL
ref: NULL
rows: 1140654
Extra: Using temporary; Using filesort
select_type: SIMPLE
table: e
type: eq_ref
possible_keys: PRIMARY,id_index
key_len: 202
ref: db.tx.userId
rows: 1
Extra: Using where