如何将同一个表的两个查询放在一起

时间:2013-01-07 22:20:16

标签: mysql sql

将两个查询加入一个查询时遇到问题。

查询1:

SELECT *
FROM (`text`)
WHERE `text` LIKE '%TERM1%' ORDER BY `text`.`start` DESC

查询2:

SELECT *,
  MATCH (col1,  col2,  col3) AGAINST ('%TERM2%' IN BOOLEAN MODE) AS relevance
FROM `text`
WHERE MATCH (col1, col2, col3) AGAINST ('%TERM2%' IN BOOLEAN MODE)
      AND status=2
ORDER BY `text`.`start` DESC

任何建议都会被接受。

表'文字'看起来像

+-------+--------+-------+------+------+
|  col1 |  col2  | col3  | text |  id  |
+-------+--------+-------+------+------+
| name1 | place1 | date1 | val1 |   1  |
| name2 | place2 | date2 | val2 |   2  |
| name3 | place2 | date5 | val1 |   3  |
| name4 | place4 | date4 | val5 |   4  |
| name5 | place5 | date5 | val5 |   5  |
:
:
| namex | placex | datex | valx |   x  |
+-------+--------+-------+------+------+

我忘了写,第一个查询也必须通过启动DESC命令...

我希望结果如:term1 = val1,term2 = val5

+-------+--------+-------+------+------+
|  col1 |  col2  | col3  | text |  id  |
+-------+--------+-------+------+------+

qery1结果:

| name3 | place2 | date5 | val1 |   3  |
| name1 | place1 | date1 | val1 |   1  |

query2 result

| name5 | place5 | date5 | val5 |   5  |
| name4 | place4 | date4 | val5 |   4  |
:
:
| namex | placex | datex | valx |   1  |
+-------+--------+-------+------+------+

感谢。

@PinnyM - 是的表名为text,而且在表格列text内,不幸的是,我已经采用了完整的数据库项目,这很荒谬,但也很荒谬地改变完整代码,因为有必要或不更改表名。

1 个答案:

答案 0 :(得分:1)

这是一种方式:

SELECT t.*, -1 as relevance
FROM `text` t
WHERE `text` LIKE '%TERM1%'
union all
SELECT t.*, MATCH (col1,  col2,  col3) AGAINST ('%TERM2%' IN BOOLEAN MODE) AS relevance
FROM `text` t
WHERE MATCH (col1, col2, col3) AGAINST ('%TERM2%' IN BOOLEAN MODE) AND status=2
ORDER BY `text`.`start` DESC