2012-03-10 67 views
0

我試圖找到一種方法來創建從數據庫查詢中的結果計算來提供一種相關性。爲每一行選擇計算

這裏是我的查詢的例子:

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個計算字段計算總計?

回答

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) 
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; 

查詢引擎可能是足夠聰明,只計算一次,即使它被提及兩次,頭腦簡單的方式匹配:

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。