我正在查询3个表和1个视图
表1 ='信息'
id int(11) PK
name varchar(45)
industry int(11)
...alot more columns.
表2 ='行业'
id int(11) PK
type varchar(45)
查看1 ='event_entrys'
id int(11)
eventName varchar(45)
hraScreened tinyint
hraBmi decimal(10,2)
hraWaist decimal(10,2)
gender tinyint
...a lot more columns.
查看(event_entrys
)='569e98bd-eb23-11e3-b215-00059a3c7800'
id int(11)
eventName varchar(45)
hraScreened tinyint
hraBmi decimal(10,2)
hraWaist decimal(10,2)
gender tinyint
...a lot more columns.
view.eventName中的值是从information.name。
插入的(SELECT COUNT(*) FROM `event_entrys` AS ee WHERE ee.`hraScreened` = 1 AND ee.`hraBmi` > 0 AND ee.`hraBmi` NOT BETWEEN 18.5 AND 25 AND ee.`hraWaist` > IF(ee.`gender` = 0, 102, 88) AND
(SELECT `industry` FROM `information` WHERE `name` = ee.`clientName`) IN (SELECT inf1.`industry` FROM `information` AS inf1 INNER JOIN `569e98bd-eb23-11e3-b215-00059a3c7800` AS ee2 ON inf1.`name` = ee2.`clientName` GROUP BY inf1.`industry`))
以上查询我在一个很长的mysql过程中使用。
但是上面的查询在开始的一段时间内返回0并且在执行它之后几次开始返回28(例如任何数字但不是0)
单独运行时,此查询对于我的条件中的28条记录为真
SELECT COUNT(*) FROM `569e98bd-eb23-11e3-b215-00059a3c7800` AS ee WHERE ee.`hraScreened` = 1 AND ee.`hraBmi` > 0 AND ee.`hraBmi` NOT BETWEEN 18.5 AND 25
ee。clientName
='有针对性的医疗计划'
ee2。clientName
='有条件的医疗计划'
单独运行时,此查询返回整数17
SELECT `industry` FROM `information` WHERE `name` = ee.`clientName`
单独运行时,此查询返回整数17
SELECT inf1.`industry` FROM `information` AS inf1 INNER JOIN `569e98bd-eb23-11e3-b215-00059a3c7800` AS ee2 ON inf1.`name` = ee2.`clientName` GROUP BY inf1.`industry`
我已经尝试了很多,但我无法弄清楚我做错了什么... 任何帮助都将受到高度赞赏。
答案 0 :(得分:0)
重新编码您使用连接的长查询,从而避免尝试检查一个相关子查询的结果是否是另一个子查询的结果(我以前从未见过): -
SELECT COUNT(*)
FROM 569e98bd-eb23-11e3-b215-00059a3c7800 AS ee
INNER JOIN information inf ON inf.name = ee.clientName
WHERE ee.hraScreened = 1
AND ee.hraBmi > 0
AND ee.hraBmi NOT BETWEEN 18.5 AND 25
AND ee.hraWaist > IF(ee.gender = 0, 102, 88)
AND inf.industry
IN
(
SELECT inf1.industry
FROM information AS inf1
INNER JOIN 569e98bd-eb23-11e3-b215-00059a3c7800 AS ee2
ON inf1.name = ee2.clientName
GROUP BY inf1.industry
)
阅读本文似乎是ee上的记录,它通过在信息表中找到名称是来自ee的clientName的行来获得行业。然后,它检查结果行业是否在子查询的结果中。
然而,该子查询只是加入信息表和ee,具有相同的连接条件,但对ee行的限制较少。
据我所知,总会找到它,所以在子查询的结果中检查它是多余的。
查询可以写成: -
SELECT COUNT(*)
FROM 569e98bd-eb23-11e3-b215-00059a3c7800 AS ee
INNER JOIN information inf ON inf.name = ee.clientName
WHERE ee.hraScreened = 1
AND ee.hraBmi > 0
AND ee.hraBmi NOT BETWEEN 18.5 AND 25
AND ee.hraWaist > IF(ee.gender = 0, 102, 88)