这应该为您解决问题:
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 秒内返回,第二个查询在半秒内返回。
不同之处在于,使用 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)