2017-07-31 47 views
1

我的查詢從3個表中選擇數據,將結果設置爲'title'(一個表具有'description'作爲我需要查看的列)。我還創建了一個結果'doctype',其值表示它後來發現哪個表用於前端過濾器。然後,它通過訂單:具有union的子查詢計數全部

  1. 結果與搜索關鍵詞開始
  2. 結果中包含搜索關鍵詞中間的某個位置
  3. 結果與搜索關鍵詞結束

我需要的是得到計數爲每個查詢中的子查詢:

SELECT * FROM (
    SELECT Title as title, 'docs' AS 'doctype' FROM docs 
    WHERE status IN ('publish', 'draft', 'review') AND Title LIKE '%' :searchterm '%' 
UNION ALL 
    SELECT Title as title, 'sheets' AS 'doctype' FROM sheets 
    WHERE status IN ('publish', 'draft', 'review') AND Title LIKE '%' :searchterm '%' 
UNION ALL 
    SELECT Description AS title, 'pres' AS 'doctype' from presentations 
    WHERE status IN ('publish', 'draft', 'review') AND Description LIKE '%' :searchterm '%' 
) FINAL 
    ORDER BY 
     CASE 
     WHEN title LIKE :searchterm '%' THEN 1 
     WHEN title LIKE '%' :searchterm THEN 3 
     ELSE 2 
     END 
    LIMIT 300 

並且還確認可以使用al i在ORDER BY中的名稱('標題')。

+0

關閉我的頭頂我的解決辦法是單獨運行這些搜索詞和數着,但是這可能是最糟糕的方式^^ – GrumpyCrouton

+0

你不能同時擁有mysql和sql-server - 請刪除無關標籤。 – Eli

+0

謝謝@Eli,已完成 – DJC

回答

0

添加一個計數域和GROUPBY子句中的子查詢

修訂

SELECT 
(SELECT count(*) FROM docs WHERE status IN ('publish', 'draft', 'review') AND Title LIKE '%' :searchterm '%') as 'count_docs' 
,(SELECT count(*) FROM sheets WHERE status IN ('publish', 'draft', 'review') AND Title LIKE '%' :searchterm '%') as 'count_sheets' 
,(SELECT count(*) FROM presentations WHERE status IN ('publish', 'draft', 'review') AND Description LIKE '%' :searchterm '%') as 'count_pres' 
, FINAL.* 
FROM (
    SELECT Title as title, 'docs' AS 'doctype' FROM docs 
    WHERE status IN ('publish', 'draft', 'review') AND Title LIKE '%' :searchterm '%' 
UNION ALL 
    SELECT Title as title, 'sheets' AS 'doctype' FROM sheets 
    WHERE status IN ('publish', 'draft', 'review') AND Title LIKE '%' :searchterm '%' 
UNION ALL 
    SELECT Description AS title, 'pres' AS 'doctype' from presentations 
    WHERE status IN ('publish', 'draft', 'review') AND Description LIKE '%' :searchterm '%' 
) as FINAL 
    ORDER BY 
     CASE 
     WHEN title LIKE :searchterm '%' THEN 1 
     WHEN title LIKE '%' :searchterm THEN 3 
     ELSE 2 
     END 
    LIMIT 300 
+0

這似乎是顯示所有結果,沒有錯誤 - 但我如何訪問3個值?現在每行似乎都有一個'cnt'值爲1.另外,爲什麼GROUP BY是必需的? – DJC

+0

@CIvemy我想我第一次錯了,現在試試更新一個。我無法自己測試,所以讓我知道是否有sql錯誤。 順便說一下,count_docs,count_sheets和count_pres的值在所有行中總是相同的。所以結果集在這方面將是多餘的。 在性能方面,最好有單獨的查詢來計算總計。 – RudiBR