0

我有这个查询要在两个 SQL 表中搜索。我正在寻找一种按事件对结果进行排序的方法。这是我的查询:

SELECT `parent_id`
FROM wp_forum_posts
WHERE text LIKE '%{$term1}%'
UNION
SELECT `id`
FROM wp_forum_threads
WHERE subject LIKE '%{$term1}%

获得排序结果的最佳方法是什么?

4

2 回答 2

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
于 2012-01-02T22:14:21.987 回答
0

假设 ID 和 parent_ID 在表中不重复,否则每个 id 可以得到 2 行...如果是这样,您是否希望它们相加在一起,那么 parent_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
于 2012-01-02T22:03:18.723 回答