我有这个SELECT:
SELECT
m.`maschine-name` AS 'byMaschine',
q.`mname` AS 'byMName'
FROM
`qualitaet` q
INNER JOIN
maschinen m ON m.maschine = q.maschine
WHERE
q.`status`='1'
GROUP BY
concat(q.maschine, q.mname)
得到这个结果:
| maschine-name | mname |
| TYP 1 | 0 |
| TYP 2 | 3 |
| TYP 2 | 4 |
| TYP 3 | 0 |
| TYP 4 | 0 |
请参阅SQL Fiddle here
然后我有几乎相同的SELECT和额外的COUNT和Datefilter:
SELECT
m.`maschine-name` AS 'byMaschine',
q.`mname` AS 'byMName',
COUNT(*) AS 'total'
FROM
`qualitaet` q
INNER JOIN
maschinen m ON m.maschine = q.maschine
WHERE
q.`created`>=NOW() - INTERVAL 2 DAY
AND
q.`status`='1'
GROUP BY
concat(q.maschine, q.mname)
得到这个结果:
| maschine-name | mname | total |
| TYP 2 | 3 | 1 |
| TYP 3 | 0 | 2 |
请参阅SQL Fiddle here
第二个SELECT没有给我所有信息。我需要两个SELECTS的混合
第二个SELECT应如下所示:
| maschine-name | mname | total |
| TYP 1 | 0 | 0 |
| TYP 2 | 3 | 1 |
| TYP 2 | 4 | 0 |
| TYP 3 | 0 | 2 |
| TYP 4 | 0 | 0 |
是否可以通过2个选项进行正确加入?或者有另一种方法来获得结果吗?
答案 0 :(得分:2)
使用条件聚合:
SELECT m.`maschine-name` AS byMaschine, q.`mname` AS byMName,
sum(q.created >= NOW() - INTERVAL 2 DAY) as Total
FROM qualitaet q INNER JOIN
maschinen m
ON m.maschine = q.maschine
WHERE q.status = '1'
GROUP BY q.maschine, q.mname;
其他建议:
GROUP BY
中的分组列 - 除非你真的,真的打算这样做(我怀疑)。status
是数字,请不要对常量使用单引号。