这篇文章主要介绍了解决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
错误的意思是指子查询结果多于一行。
报错如下

解决方法
以这个sql语句为例
select * from table1 where table1.colums=(select columns from table2);1)如果是写入重复,去掉重复数据。然后写入的时候,可以加逻辑判断(php)或者外键(mysql),防止数据重复写入。
(我实际开发中遇到的就是数据重复写入的情况,在数据库查到有相同的数据两条,这不符原本的原本的业务需求)
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
执行耗时 : 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是多条数据,而外层查询结果是要求num为一条数据
解决办法
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问题
基础教程推荐
- Mysql查看死锁与解除死锁的深入讲解 2024-02-14
- 详解Redis连接命令使用方法 2024-03-23
- 浅谈数据库优化方案 2024-02-16
- MySQL索引优化之适合构建索引的几种情况详解 2023-12-29
- 如何保障mysql和redis之间的数据一致性 2024-04-25
- mysql时间字段默认设置为当前时间实例代码 2022-08-31
- mysql服务启动却连接不上的解决方法 2023-12-08
- SQL Server之SELECT INTO 和 INSERT INTO SELECT案例详解 2024-02-13
- Redis GEORADIUS命令 2024-04-06
- Redis配置项汇总 2024-04-04
