これでうまくいくはずです:
select distinct *
from
(
SELECT
id,
title,
day,
time
FROM
$db_1
UNION ALL
SELECT
id,
title,
day,
time
FROM
$db_2
WHERE
month='$month'
AND year='$year'
)
ORDER BY time
group by を使用できますが、効率が低下します。以下のクエリで問題が発生し、最初のクエリは約 10 秒で返され、2 番目のクエリは 0.5 秒未満で返されたため、いくつかの統計を実行することになりました。
違いは、group by を使用すると、サブクエリにファイルソートが導入されることです。これが私の場合、すべての問題を引き起こしました。
mysql> EXPLAIN select
-> a.mCode as cCode,
-> a.mName as cName
-> from
-> _user_UserStructure a
-> where
-> a.pCode in
-> (
-> select
-> b.pCode
-> from
-> _user_userStructure b
-> where
-> b.mCode='RBM1'
-> and b.pCode!=b.cCode
-> group by
-> b.pCode
-> )
-> and a.cCode != ''
-> and a.pCode != a.mCode
-> and a.mCode!='RBM1'
-> group by
-> a.mCode,
-> a.mName
-> order by
-> a.mName asc;
+----+--------------------+-------+-------+---------------+-------+---------+------+------+----------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------------+-------+-------+---------------+-------+---------+------+------+----------------------------------------------+
| 1 | PRIMARY | a | ALL | cCode | NULL | NULL | NULL | 1769 | Using where; Using temporary; Using filesort |
| 2 | DEPENDENT SUBQUERY | b | index | NULL | pCode | 13 | NULL | 2 | Using where; Using filesort |
+----+--------------------+-------+-------+---------------+-------+---------+------+------+----------------------------------------------+
2 rows in set (0.00 sec)
mysql> EXPLAIN select distinct
-> a.mCode as cCode,
-> a.mName as cName
-> from
-> _user_UserStructure a
-> where
-> a.pCode in
-> (
-> select distinct
-> b.pCode
-> from
-> _user_userStructure b
-> where
-> b.mCode='RBM1'
-> and b.pCode!=b.cCode
-> )
-> and a.cCode != ''
-> and a.pCode != a.mCode
-> and a.mCode!='RBM1'
-> order by
-> a.mName asc;
+----+--------------------+-------+----------------+---------------+-------+---------+------+------+----------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------------+-------+----------------+---------------+-------+---------+------+------+----------------------------------------------+
| 1 | PRIMARY | a | ALL | cCode | NULL | NULL | NULL | 1769 | Using where; Using temporary; Using filesort |
| 2 | DEPENDENT SUBQUERY | b | index_subquery | pCode | pCode | 13 | func | 2 | Using where |
+----+--------------------+-------+----------------+---------------+-------+---------+------+------+----------------------------------------------+
2 rows in set (0.00 sec)