SET @H_CODE = '00000';
SET @BEGIN_DATE = '20171001';
SET @END_DATE = '20180331';
DELETE FROM random_audit_opd WHERE HCODE = @H_CODE;
INSERT IGNORE INTO random_audit_opd (HCODE,PID,HN,DATE_SERV,DCODE)
SELECT * FROM (
(SELECT
service.HCODE,
service.PID,
service.HN,
service.DATE_SERV,
dnosis_op.DCODE
FROM
service
JOIN dnosis_op
ON service.HCODE = dnosis_op.HCODE
AND service.PID = dnosis_op.PID
AND service.SEQ = dnosis_opd.SEQ
WHERE
service.HCODE = @H_CODE
AND service.DATE_SERV BETWEEN @BEGIN_DATE AND @END_DATE
AND dnosis_op.DIAGCODE BETWEEN 'a' AND 'b99'
ORDER BY RAND()
LIMIT 3)
UNION
(SELECT
service.HCODE,
service.PID,
service.HN,
service.DATE_SERV,
dnosis_op.DCODE
FROM
service
JOIN dnosis_op
ON service.HCODE = dnosis_op.HCODE
AND service.PID = dnosis_opd.PID
AND service.SEQ = dnosis_op.SEQ
WHERE
service.HCODE = @H_CODE
AND service.DATE_SERV BETWEEN @BEGIN_DATE AND @END_DATE
AND dnosis_opd.DCODE BETWEEN 'd50' AND 'd89'
ORDER BY RAND()
LIMIT 2)
UNION
(SELECT
service.HCODE,
service.PID,
service.HN,
service.DATE_SERV,
dnosis_op.DCODE
FROM
service
JOIN dnosis_opd
ON service.HCODE = dnosis_op.HCODE
AND service.PID = dnosis_op.PID
AND service.SEQ = dnosis_op.SEQ
WHERE
service.HCODE = @H_CODE
AND service.DATE_SERV BETWEEN @BEGIN_DATE AND @END_DATE
AND dnosis_op.DCODE LIKE 'e%'
ORDER BY RAND()
LIMIT 2)
UNION
(SELECT
service.HCODE,
service.PID,
service.HN,
service.DATE_SERV,
dnosis_op.DCODE
FROM
service
JOIN dnosis_op
ON service.HCODE = dnosis_op.HCODE
AND service.PID = dnosis_op.PID
AND service.SEQ = dnosis_op.SEQ
WHERE
service.HCODE = @H_CODE
AND service.DATE_SERV BETWEEN @BEGIN_DATE AND @END_DATE
AND dnosis_op.DCODE LIKE 'i%'
ORDER BY RAND()
LIMIT 2)