因此,我有以下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)
子查询本身可以正常工作,但是它返回两列(filmid
和common_tag_count
),这意味着它会导致可预测的“操作数应包含1列”错误。
但是我不想让子查询仅返回filmid
列,我想将common_tag_count
列添加到查询的最终结果中。这可能吗?
答案 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