将另一个表添加到mySQL查询中

时间:2012-01-21 00:20:16

标签: mysql sql

到目前为止,我有以下SQL查询,效果很好:

SELECT *,
  MATCH(title, content_plain_text) AGAINST ('$searchTerm') AS score, 
  (MATCH(title, content_plain_text) AGAINST ('$searchTerm') / maxScore) AS normalisedScore
FROM pages,
  (SELECT MAX(MATCH(title, content_plain_text) AGAINST ('$searchTerm')) AS maxScore 
    FROM pages) maxScoreTable
    WHERE MATCH(title, content_plain_text) AGAINST ('$searchTerm')
    AND active = 1
    ORDER BY score DESC

所以现在我想搜索另一个具有相同字段名称的表,如何在保持排名等的同时进行此操作?

谢谢!

1 个答案:

答案 0 :(得分:0)

我只是union all您的pages表与另一个表(假设其名为more_pages)。

WITH构造确实很适合这些问题,但不幸的是MySQL还不支持它。 我能提出的最优雅的选择是创建一个封装这个联合的视图:

CREATE VIEW all_pages AS
SELECT * FROM pages
UNION ALL
SELECT * FROM more_pages


SELECT *,
  MATCH(title, content_plain_text) AGAINST ('$searchTerm') AS score, 
  (MATCH(title, content_plain_text) AGAINST ('$searchTerm') / maxScore) AS normalisedScore
FROM all_pages,
  (SELECT MAX(MATCH(title, content_plain_text) AGAINST ('$searchTerm')) AS maxScore 
    FROM all_pages) maxScoreTable
    WHERE MATCH(title, content_plain_text) AGAINST ('$searchTerm')
    AND active = 1
    ORDER BY score DESC