高级MySQL离开加入IFNULL查询

时间:2015-04-30 14:05:06

标签: mysql mariadb

我正在寻找有关高级MySQL查询的帮助。我当前的查询,如下所示,工作正常。我想添加一个额外的字段,因此我不必创建单独的查询。新字段count(TableA.Field05)应该会产生TableA的记录总数。

TableA有10条记录 TableB有100条记录

SELECT count(TableB.Answer) AS unAnswered 
FROM TableA 
LEFT JOIN TableB 
ON ( TableA.Field01 = TableB.fkField01 AND TableA.Field02 = TableB.fkField02 AND TableB.Answer = '1') 
WHERE TableB.fkField03 IS NULL AND TableA.Field04 = 10 
GROUP BY TableA.Field01, TableA.Field02

结果:

unAnswered = 8这是正确的

期望的结果是:

unAnswered = 8 count(TableA.Field05) = 10

-

这是数据和结果的一个例子。

SELECT count(TableB.Answer) AS unAnswered
FROM TableA LEFT JOIN TableB ON ( TableA.Field01 = TableB.fkField01 AND TableA.Field02 = TableB.fkField02 AND TableB.Answer = '1')
WHERE TableB.fkField03 IS NULL AND TableA.Field04 = 10
GROUP BY TableA.Field01, TableA.Field02

TableA
Field01 = 1, Field02 = 1, Field03 = 10
Field01 = 1, Field02 = 2, Field03 = 21
Field01 = 1, Field02 = 3, Field03 = 22
Field01 = 1, Field02 = 4, Field03 = 34

TableB
Field01 = 1, Field02 = 1, Answer = 1
Field01 = 1, Field02 = 2, Answer = 1
Field01 = 1, Field02 = 3, Answer = 1
Field01 = 2, Field02 = 1, Answer = 1
Field01 = 2, Field02 = 2, Answer = 1
Field01 = 2, Field02 = 3, Answer = 1

Result
count(TableB.Answer) AS unAnswered = 1


Result trying to achive
count(TableB.Answer) AS unAnswered = 1
count(TableA.Field03) = 4

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

如果您只想将tableA的数量添加到当前查询中,只需将其添加到您的select语句中:

'SELECT count(TableB.Answer)AS unAnswered,count(TableA.Field02)FROM TableA ...'