次のクエリがあります:
select `privmsgs_id`, `contact`, `privmsgs_date`, `contentType` from (
(
select max(`privmsgs_id`) as `privmsgs_id`, `contact`, max(`privmsgs_date`) as `privmsgs_date`, `contentType` from (
(
select `privmsgs_from_userid` as `contact`, `privmsgs_id`, `privmsgs_date`, 'message' as `contentType`
from `privmsgs_table`
where `privmsgs_to_userid` = 305026
) union (
select `privmsgs_to_userid` as `contact`, `privmsgs_id`, `privmsgs_date`, 'message' as `contentType`
from `privmsgs_table`
where `privmsgs_from_userid` = 305026
)
) as `tmp` group by `contact` order by `privmsgs_date` desc
) union (
select max(`privmsgs_id`) as `privmsgs_id`, `contact`, max(`privmsgs_date`) as `privmsgs_date`, `contentType` from (
(
select `from_userid` as `contact`, `id` as `privmsgs_id`, `date` as `privmsgs_date`, 'postcard' as `contentType`
from `postcards_table`
where `to_userid` = 305026
) union (
select `to_userid` as `contact`, `id` as `privmsgs_id`, `date` as `privmsgs_date`, 'postcard' as `contentType`
from `postcards_table`
where `from_userid` = 305026
)
) as `tmp1` group by `contact` order by `privmsgs_date` desc
)
) as `rTmp` order by `privmsgs_date` desc;
2 つのテーブルがありtmp
、tmp1
ユニオンによってマージされていますが、フィールドが 2 倍になっていますcontact
。
privmsgs_id contact privmsgs_date contentType
21490780 7070 1315207813 message
21556868 7070 1315215266 postcard
21226460 7754 1312025735 message
21539085 15588 1314615528 postcard
21489812 15588 1315208838 message
したがって、最後のレコード (メッセージまたはポストカード - 重要ではありません) とこの最後のレコードの ID (問題があります - メッセージとポストカードを別々に max(id) を取得できますが、マージされたテーブルでは取得できません) のみが必要です。 ):
privmsgs_id contact privmsgs_date contentType
21556868 7070 1315215266 postcard
21226460 7754 1312025735 message
21489812 15588 1315208838 message
クエリを単純化しない理由は、特定の数の結果が必要なためです。これは、1 つのクエリでしか実行できません。