我得到了第二级儿童记录的选择声明,有更深层次的问题,任何人都可以帮忙吗?
SELECT
id_mobile AS ID_PROJETO,
UM.qtd_UC,
AM.qtd_AMBIENTE
FROM projetos_mobile AS PM
LEFT JOIN (
SELECT
COUNT(id) AS qtd_UC,
projeto,
data_hora_importacao,
id_uc_mobile
FROM ucs_mobile
WHERE data_hora_importacao = '2015-05-15 17:21:02'
GROUP BY projeto) AS UM
ON PM.id_mobile = UM.projeto
LEFT JOIN (
SELECT
COUNT(id_uc_mobile) AS qtd_AMBIENTE,
id_uc_mobile
FROM ucs_mobile
LEFT JOIN (
SELECT
uc
FROM ambientes_mobile AS s
WHERE data_hora_importacao = '2015-05-15 17:21:02') AS G
ON G.uc = ucs_mobile.id_uc_mobile
WHERE data_hora_importacao = '2015-05-15 17:21:02') AS AM
ON UM.id_uc_mobile = AM.id_uc_mobile
WHERE PM.data_hora_importacao = '2015-05-15 17:21:02'
http://sqlfiddle.com/#!9/2eecf
如果有人想尝试解决方案,这里是一个平方米。我有特定的层次结构:projeto> uc> ambiente> secao> medicoes
ucs_mobile.projeto refers to projetos_mobile.id_mobile
ambientes_mobile.uc refers to ucs_mobile.id_uc_mobile
secoes_iluminacao_mobile.ambiente refers to ambientes_mobile.id_ambiente_mobile
我需要为我通过的父母计算每个孩子的数量,我将有5个功能 返回给定父母的每个孩子的计数,例如,对于一个projeto父母我应该有计数(ucs),count(ambientes),count(secoes),count(medicoes)
所以,希望你们能帮助我。数据库很丑陋,但这就是我所得到的。感谢任何帮助。
答案 0 :(得分:1)
当你有这样的大型查询时,从头开始并将它们拼凑在一起可能有助于将它们单独分解。
我首先得到每个projetos_mobile值的每个ucs_mobile行的计数。您可以通过连接相关行上的两个表,并使用COUNT(DISTINCT um.id)
来获取行数。还有其他方法可以做到这一点,但这种特殊方法可以更好地扩展到查询的其余部分:
SELECT pm.id, COALESCE(COUNT(DISTINCT um.id), 0) AS qty_uc
FROM projetos_mobile pm
LEFT JOIN ucs_mobile um ON um.data_hora_importacao = '2015-05-15 17:21:02' AND um.projeto = pm.id_mobile
GROUP BY pm.id;
COALESCE功能将用于填充0计数。只要您记得使用DISTINCT
关键字,并按正确的id
进行分组,您就可以像这样添加子行:
SELECT
pm.id,
COALESCE(COUNT(DISTINCT um.id), 0) AS qty_uc,
COALESCE(COUNT(DISTINCT am.id), 0) AS qty_am,
COALESCE(COUNT(DISTINCT sim.id), 0) AS qty_sim
FROM projetos_mobile pm
LEFT JOIN ucs_mobile um ON um.data_hora_importacao = '2015-05-15 17:21:02' AND um.projeto = pm.id_mobile
LEFT JOIN ambientes_mobile am ON am.data_hora_importacao = um.data_hora_importacao AND am.uc = um.id_uc_mobile
LEFT JOIN secoes_iluminacao_mobile sim ON sim.data_hora_importacao = am.data_hora_importacao AND sim.ambiente = am.id_ambiente_mobile
GROUP BY pm.id;
这是一个SQL Fiddle示例。 注意我稍微更改了您的示例数据,以确保我的查询按预期工作。
另外,附注。我注意到你继续使用WHERE
条款中的相同日期,所以我也在日期加入了每个表格,并确保在我第一次加入时我查找了指定的日期,反过来,它将进入其他表格。