我有这个查询在两个SQL表中搜索。我正在寻找一种方法来按事件排序结果。这是我的问题:
SELECT `parent_id`
FROM wp_forum_posts
WHERE text LIKE '%{$term1}%'
UNION
SELECT `id`
FROM wp_forum_threads
WHERE subject LIKE '%{$term1}%
获得结果的最佳方法是什么?
答案 0 :(得分:1)
诀窍是首先使用UNION ALL
,它保留重复项(普通UNION
删除重复项),然后从该结果中选择。这个查询应该这样做:
select * from (
select parent_id as mID, count(*) as cnt
from wp_forum_posts
where text like '%{$term1}%'
group by 1
UNION ALL
select id, count(*)
FROM wp_forum_threads
where subject like '%{$term1}%
group by 1) x
order by 2, 1
答案 1 :(得分:0)
假设ID和parent_ID在表中不重复,否则每个id可以获得2行......如果是,那么你是否希望将它们相加在一起?与父ID和ID相关?
Select mID, cnt
FROM
(SELECT `parent_id` as mID, count(`parent_ID`) as cnt
FROM wp_forum_posts
WHERE text LIKE '%{$term1}%'
Group by `parent_ID`
UNION
SELECT `id`, count(`id`) as cnt
FROM wp_forum_threads
WHERE subject LIKE '%{$term1}%
GROUP BY `id`)
Order by cnt ASC, mID