共計 1461 個字符,預計需要花費 4 分鐘才能閱讀完成。
這篇文章主要介紹了 mysql 錯誤 Subquery returns more than 1 row 怎么解決的相關知識,內(nèi)容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇 mysql 錯誤 Subquery returns more than 1 row 怎么解決文章都會有所收獲,下面我們一起來看看吧。
mysql 錯誤:Subquery returns more than 1 row
mysql 報錯:SQLSTATE[21000]: Cardinality violation: 1242 Subquery returns more than 1 row
錯誤的意思是指子查詢結(jié)果多于一行。
報錯如下
解決方法
以這個 sql 語句為例
select * from table1 where table1.colums=(select columns from table2);
1)如果是寫入重復,去掉重復數(shù)據(jù)。然后寫入的時候,可以加邏輯判斷 (php) 或者外鍵(mysql),防止數(shù)據(jù)重復寫入。
(我實際開發(fā)中遇到的就是數(shù)據(jù)重復寫入的情況,在數(shù)據(jù)庫查到有相同的數(shù)據(jù)兩條,這不符原本的原本的業(yè)務需求)
2)在子查詢條件語句加 limit 1, 找到一個符合條件的就可以了
select * from table1 where table1.colums=(select columns from table2 limit 1);
3)在子查詢前加 any 關鍵字
select * from table1 where table1.colums=any(select columns from table2);
錯誤代碼:1242 Subquery returns more than 1 row 錯誤描述
1 queries executed, 0 success, 1 errors, 0 warnings
查詢:SELECT t.id, DATE_FORMAT(t.statisTime, %Y-%m-%d %H:%i:%s) statisTime, (SELECT `id` FROM t_truck_info WHERE id = t.plateId…
錯誤代碼:1242Subquery returns more than 1 row
執(zhí)行耗時 : 0.009 sec 傳送時間 : 0.002 sec 總耗時 : 0.012 sec
錯誤原因
在編寫查詢 SQL 語句時,其中有個字段是從另一張表里獲取
select t.id,(select num from t_user_info where id = stuNo) as amount from t_stu_info t left join t_user_info t0
on t0.id = t.stuNo
查詢出 num 是多條數(shù)據(jù),而外層查詢結(jié)果是要求 num 為一條數(shù)據(jù)
解決辦法
select t.id,(select sum(num) from t_user_info where id = stuNo) as amount from t_stu_info t left join t_user_info t0
on t0.id = t.stuNo
關于“mysql 錯誤 Subquery returns more than 1 row 怎么解決”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對“mysql 錯誤 Subquery returns more than 1 row 怎么解決”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注丸趣 TV 行業(yè)資訊頻道。
向 AI 問一下細節(jié)
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!