2017-10-13 175 views
0

我使用這個查詢來搜索標籤相似MYSQL:基數衝突:1242子查詢返回多於1行?

SELECT sites_id 
    FROM tags_to_sites 
    WHERE tags_id IN (SELECT tags_id FROM tags_to_sites WHERE sites_id= ?) 
    AND sites_id!= ? 
    GROUP BY sites_id 
    HAVING COUNT(*) = ( SELECT COUNT(*) FROM tags_to_sites 
    WHERE tags_id IN (SELECT tags_id FROM tags_to_sites WHERE sites_id= ?) 
     AND sites_id!= ? 
    GROUP BY sites_id 
    ORDER BY COUNT(*) DESC LIMIT 3) 

,但我得到一個錯誤

SQLSTATE [21000]:基數違規:1242子查詢返回多個 比1排

有人知道爲什麼嗎?

+0

你的子查詢返回3行(由'ORDER BY COUNT(*)DESC LIMIT 3'),你必須只返回1或重寫你的'having'聲明' (#)在' – SatanDmytro

+0

好抓!所以我如何限制最終數組只有3個結果? shoudl我在限制範圍外移動限制3? – Francesco

+0

你可以從表中添加一些數據並解釋你想要的查詢嗎? – SatanDmytro

回答

0

正確的查詢

SELECT sites_id 
    FROM tags_to_sites 
    WHERE tags_id IN (SELECT tags_id FROM tags_to_sites WHERE sites_id= ?) 
    AND sites_id!= ? 
    GROUP BY sites_id 
    HAVING COUNT(*) = ( SELECT COUNT(*) FROM tags_to_sites 
    WHERE tags_id IN (SELECT tags_id FROM tags_to_sites WHERE sites_id= ?) 
     AND sites_id!= ? 
    GROUP BY sites_id 
    ORDER BY COUNT(*) DESC LIMIT 1) 
LIMIT 3 
相關問題