从MySQL子查询添加额外的列到查询结果

时间:2019-08-09 19:52:41

标签: mysql select subquery

因此,我有以下SQL查询,该查询应返回Film表中的所有项目,并按它们与具有filmid=2的影片的共有标签数量进行排序:

SET @id = 2;
SELECT * FROM Films
WHERE id IN
    (SELECT at1.filmid,
            Count(at1.tagid) AS common_tag_count
     FROM Taggings AS at1
     INNER JOIN Taggings AS at2 ON at1.tagid = at2.tagid
     WHERE at2.filmid = @id
     GROUP BY at1.filmid
     HAVING at1.filmid != @id
     ORDER BY common_tag_count DESC)

子查询本身可以正常工作,但是它返回两列(filmidcommon_tag_count),这意味着它会导致可预测的“操作数应包含1列”错误。

但是我不想让子查询仅返回filmid列,我想将common_tag_count列添加到查询的最终结果中。这可能吗?

1 个答案:

答案 0 :(得分:1)

我将计数作为嵌入式视图进行,并加入Films表。像这样

SELECT f.*
     , c.common_tag_count
  FROM Films f
  JOIN ( -- inline view/derived table
         SELECT at1.filmid
              , COUNT(at1.tagid) AS common_tag_count
           FROM Taggings at1
           JOIN Taggings at2
             ON at2.tagid = at1.tagid
          WHERE at2.filmid   = @id
          GROUP
             BY at1.filmid
         HAVING at1.filmid  != @id
       ) c
    ON c.filmid = f.id   
 ORDER 
    BY c.common_tag_count DESC
     , f.id