子查询计数与union all

时间:2017-07-31 15:10:03

标签: php mysql sql pdo

我的查询从3个表中选择数据,将结果设置为' title' (一个表格有'描述'作为我需要查看的列)。我还创建了一个结果' doctype'带有一个值,表示稍后用于前端过滤器的表格。然后按顺序排序:

  1. 结果以searchterm
  2. 开头
  3. 结果在中间某处包含searchterm
  4. 结果以searchterm结尾
  5. 我需要的是获取查询中每个子查询的计数:

    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
    

    还要确认在ORDER BY中使用别名(' title')是可以的。

1 个答案:

答案 0 :(得分:0)

在子查询中添加count字段和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