解決mysql錯誤:Subquery?returns?more?than?1?row問題
mysql錯誤:Subquery returns more than 1 row
mysql報(bào)錯:SQLSTATE[21000]: Cardinality violation: 1242 Subquery returns more than 1 row
錯誤的意思是指子查詢結(jié)果多于一行。
報(bào)錯如下
解決方法
以這個sql語句為例
select * from table1 where table1.colums=(select columns from table2);
1)如果是寫入重復(fù),去掉重復(fù)數(shù)據(jù)。然后寫入的時候,可以加邏輯判斷(php)或者外鍵(mysql),防止數(shù)據(jù)重復(fù)寫入。
(我實(shí)際開發(fā)中遇到的就是數(shù)據(jù)重復(fù)寫入的情況,在數(shù)據(jù)庫查到有相同的數(shù)據(jù)兩條,這不符原本的原本的業(yè)務(wù)需求)
2)在子查詢條件語句加limit 1,找到一個符合條件的就可以了
select * from table1 where table1.colums=(select columns from table2 limit 1);
3)在子查詢前加any關(guān)鍵字
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
總結(jié)
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
MySQL執(zhí)行SQL文件報(bào)錯:Unknown collation ‘utf8mb4_0900_ai_
這篇文章主要給大家分享了MySQL執(zhí)行SQL文件出現(xiàn)【Unknown collation ‘utf8mb4_0900_ai_ci‘】的解決方案,如果又遇到相同問題的同學(xué),可以參考閱讀本文2023-09-09MySQL delete刪除數(shù)據(jù)后釋放磁盤空間的操作方法
這篇文章主要介紹了MySQL delete刪除數(shù)據(jù)后,釋放磁盤空間,文中給大家介紹了優(yōu)化表空間的多種方法,每種方法給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-05-05Mysql中 show table status 獲取表信息的方法
這篇文章主要介紹了Mysql中 show table status 獲取表信息的方法的相關(guān)資料,需要的朋友可以參考下2016-03-03mysql使用from與join兩表查詢的區(qū)別總結(jié)
這篇文章主要給大家介紹了關(guān)于mysql使用from與join兩表查詢的區(qū)別的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-12-12