0

我想按 DESC 的总和两列image_gallery排序video_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_gallery获得.video_gallerysum_gallery

我该如何解决?

4

3 回答 3

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
于 2018-10-30T21:55:18.050 回答
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'
于 2018-10-30T21:55:31.137 回答
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
于 2018-10-30T21:54:16.013 回答