简体   繁体   English

带有条件的MySQL子查询,结果不同

[英]Mysql subqueries with conditions, different results

I'm having a problem with a project I'm working on. 我正在处理的项目有问题。

I have 2 tables. 我有2张桌子。 First table is workorder . 第一个表是工作workorder This table consists of the following columns: 该表包括以下列:

  • id ID
  • relation_code 相关代码
  • generated 产生的
  • exportready 准备出口

Second table is workorder_records . 第二个表是workorder_records Columns: 列:

  • id ID
  • workorder_id workorder_id
  • description 描述
  • approved 已批准

I need to select every workorder where generated = 0 and exportready = 0 and its records count. 我需要选择生成= 0且exportready = 0及其记录计数的每个工作workorder But, only records where approved = 0 and description != ''. 但是,仅记录批准= 0且描述!=”的记录。

I've written this query for it: 我已经为此查询写了:

SELECT *, (SELECT COUNT(*) FROM workorder_records
WHERE workorder_records.approved = 0
AND workorder_records.workorder_id = workorder.id
AND workorder_records.description != ''
) as totalunapproved
FROM workorder
WHERE workorder.generated = 0
AND workorder.exportready = 0

I get the correct result when I execute this in phpMyAdmin. 当我在phpMyAdmin中执行此操作时,我得到正确的结果。 When I run this through a PHP script connected to the same database, I get different results. 当我通过连接到相同数据库的PHP脚本运行此脚本时,会得到不同的结果。 For example, a result where workorder_records.description was actually empty but still returned by the query function. 例如,结果workorder_records.description实际上为空,但仍由查询函数返回。

SQL Fiddle Link: http://sqlfiddle.com/#!2/ea8aa/3 SQL小提琴链接: http ://sqlfiddle.com/#!2/ea8aa/3

Any help is appreciated. 任何帮助表示赞赏。

Edit: I solved the problem by doing the checks in PHP. 编辑:我通过在PHP中进行检查解决了问题。 This is of course not ideal but I just can't figure out why the conditional subquery works in PHPMyAdmin and not in my PHP script. 这当然不是理想的,但是我只是想不出为什么条件子查询在PHPMyAdmin中而不是在我的PHP脚本中起作用。

Try to replace this 尝试取代这个

workorder_records.description != ''

to

workorder_records.description IS NOT NULL

And make workorder_records.description by default as null. 并默认将workorder_records.description设置为null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM