mysql子查詢中的any_value與where in失效
問題描述:
select * from test where id in (select any_value(id) from test group by type);
雖然預期輸出每個分組的第一行記錄,但結果卻返回了整個表。
問題分析:
問題一:
使用any_value函數的子查詢會導致where in失效。因為any_value函數返回任意一行匹配記錄的值,它不保證返回唯一值,這可能會導致where in比較失敗。
問題二:
如果在子查詢中省略as id別名,mysql將無法找到select id from …語句中的id列,因為子查詢沒有命名其結果列。在這種情況下,mysql會嘗試自動生成列名,這可能會導致不確定的行為,例如返回整個表。
解決方案:
問題一:
使用group by和min函數返回每個分組的最小id值,從而確保返回唯一值:
select * from test where id in (select min(id) from test group by type);
問題二:
顯式指定子查詢結果列的別名:
select * from test where id in (select id from (select any_value(id) as id from test GROUP BY type) as temp);
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END