我正在尝试找到一种方法来从数据库查询中的结果创建计算,以提供一种相关性。
以下是我的查询示例:
SELECT d.id, MATCH (r.text) AGAINST('sleet snow rain' IN BOOLEAN MODE) as r_matches, s.total_matches
FROM days d
LEFT JOIN condition_days r
ON (d.id = r.day_id AND MATCH (r.text) AGAINST('sleet snow rain' IN BOOLEAN MODE))
LEFT JOIN (SELECT ss.day_id, COUNT(DISTINCT ss.condition_id) as total_matches FROM conditions ss WHERE ss.condition_id IN (4, 13, 20) GROUP BY ss.day_id) s
ON (s.day_id = d.id)
返回的内容如下:
+-----+-----------+---------------+
| id | r_matches | total_matches |
+-----+-----------+---------------+
| 540 | 2 | 5 |
+-----+-----------+---------------+
所以我的问题是,如何计算2个计算字段(r_matches和total_matches)? 这是我正在寻找的一个例子:
+-----+-----------+---------------+----------------------------------------------+
| id | r_matches | total_matches | total |
+-----+-----------+---------------+----------------------------------------------+
| 540 | 2 | 3 | 5 (calculation of total_matches + r_matches) |
+-----+-----------+---------------+----------------------------------------------+
那么有没有办法从2个计算字段中获得计算总数?
答案 0 :(得分:2)
无法在没有模式的情况下测试运行,但使用临时变量这样的事情应该可以正常运行;
SELECT
d.id,
@tmp := (MATCH (r.text) AGAINST('sleet snow rain' IN BOOLEAN MODE)) as r_matches,
s.total_matches,
s.total_matches + @tmp AS total
FROM days d
LEFT JOIN condition_days r
ON (d.id = r.day_id AND MATCH (r.text) AGAINST('sleet snow rain' IN BOOLEAN MODE))
LEFT JOIN (
SELECT ss.day_id, COUNT(DISTINCT ss.condition_id) as total_matches
FROM conditions ss WHERE ss.condition_id IN (4, 13, 20) GROUP BY ss.day_id) s
ON (s.day_id = d.id)
答案 1 :(得分:0)
您可以使用派生表:
select id, r_matches, total_matches, r_matches + total_matches as total
from (
select d.id,
MATCH (r.text) AGAINST('sleet snow rain' IN BOOLEAN MODE) as r_matches,
s.total_matches as total_matches
...
) as dt;
查询引擎可能足够智能,只计算一次MATCH,即使它被提及两次,所以简单的方法:
select d.id,
MATCH (r.text) AGAINST('sleet snow rain' IN BOOLEAN MODE) as r_matches,
s.total_matches,
MATCH (r.text) AGAINST('sleet snow rain' IN BOOLEAN MODE) + s.total_matches as total
...
可能会正常工作。我不知道MySQL是否会识别重复的MATCH。