来自别名未知列的MySQL总和

时间:2018-10-30 21:31:37

标签: mysql

我要按DESC顺序对两列image_galleryvideo_gallery进行排序。

 SELECT
     b.*,
     c.title as category,
     (SELECT count(*)
      FROM `movie_gallery`
      WHERE parent = b.id) as image_gallery,
     (SELECT count(*)
      FROM `movie_videos`
      WHERE parent = b.id) as video_gallery,
     (image_gallery + video_gallery) as sum_gallery'
FROM
    `movies` b 
LEFT JOIN
    `category` c on c.id = b.category_id
ORDER BY
     sum_gallery DESC

当我尝试将image_galleryvideo_gallery加在一起以获得sum_gallery时,出现未知列。

我该如何解决?

3 个答案:

答案 0 :(得分:0)

您不能在同一SELECT语句中引用别名。与其使用相关子查询,不如对分组子查询使用LEFT JOIN

SELECT b.*, c.title AS category, image_gallery, video_gallery, IFNULL(image_gallery, 0) + IFNULL(video_gallery, 0) AS sum_galleries
FROM movies AS b
LEFT JOIN category AS c ON c.id = b.category_id
LEFT JOIN (
    SELECT parent, COUNT(*) AS image_gallery
    FROM movie_gallery
    GROUP BY parent) AS d ON d.parent = b.id
LEFT JOIN (
    SELECT parent, COUNT(*) AS video_gallery
    FROM movie_videos
    GROUP BY parent) AS e ON e.parent = b.id
ORDER BY sum_gallery DESC

答案 1 :(得分:0)

因为别名仅在查询输出中可用,并且您不能在同一查询的其他部分中使用它们。为此,您需要使用派生表概念,例如:

SELECT
    myTable.*
    (myTable.image_gallery + myTable.video_gallery) AS sum_gallery
FROM
    (SELECT
         b.*,
         c.title AS category,
         (SELECT count(*) FROM movie_gallery WHERE parent = b.id) AS image_gallery,
         (SELECT count(*) FROM movie_videos WHERE parent = b.id) AS video_gallery
     FROM
         movies AS b 
     LEFT JOIN
         category AS c ON c.id = b.category_id) AS myTable
ORDER BY
     sum_gallery DESC

答案 2 :(得分:0)

您不能像这样访问别名列,因为在评估查询时它们将不可用。您将必须完全使用表达式

 SELECT
     b.*,
     c.title as category,
     (SELECT count(*)
      FROM `movie_gallery`
      WHERE parent = b.id) as image_gallery,
     (SELECT count(*)
      FROM `movie_videos`
      WHERE parent = b.id) as video_gallery,
     ((SELECT count(*)
      FROM `movie_gallery`
      WHERE parent = b.id) + (SELECT count(*)
      FROM `movie_gallery`
      WHERE parent = b.id)) as sum_gallery'