简单搜索中的sql双记录

时间:2012-01-21 12:34:25

标签: sql duplicates union

我正在对我的网站进行简单的论坛搜索,从2个表中提取数据。

SELECT ft.id, ft.title, ft.date 
  FROM forum_topics ft 
  WHERE ft.title LIKE '%" .$search. "%' OR ft.body LIKE '%" .$search. "%' 
UNION SELECT fr.topic, ft.title, fr.date 
  FROM forum_replies fr 
    INNER JOIN forum_topics ft ON fr.topic=ft.id 
  WHERE fr.body LIKE '%" .$search. "%' 
ORDER BY date DESC

如果它在两个表中都找到了这个术语,那么它会重复,如果结果的id相同,我该怎么做才能显示重复的记录。

2 个答案:

答案 0 :(得分:0)

您可以尝试将UNION包装在另一个选择中,并在所有列上添加GROUP BY

SELECT g.id, g.title, g.date
FROM (
    SELECT ft.id, ft.title, ft.date 
    FROM forum_topics ft 
    WHERE ft.title LIKE '%" .$search. "%' OR ft.body LIKE '%" .$search. "%' 
    UNION
    SELECT fr.topic as id, ft.title, fr.date 
    FROM forum_replies fr 
    INNER JOIN forum_topics ft ON fr.topic=ft.id 
    WHERE fr.body LIKE '%" .$search. "%' 
) g
GROUP BY g.id, g.title, g.date
ORDER BY g.date DESC

答案 1 :(得分:0)

您可以将其包装在SELECT DISTINCT ID,title,date FROM(上面的查询)中。

或者,您可以在select-from-ft的WHERE子句中添加一行,使其在fr中不存在其id。