MySQL加入和联盟优化

时间:2011-07-03 00:53:05

标签: mysql sql optimization join union

我有这个SQL,它就像它被认为的那样,但我想有更好的方法来编写它以避免重复的句子并提高性能。

有什么建议吗?

CREATE OR REPLACE VIEW tx_oriconvocatorias_consultas AS
SELECT pubs.*, pais.nombre_es as area,
GROUP_CONCAT(DISTINCT linea_es ORDER BY linea_es SEPARATOR '\n') as linea_es,
GROUP_CONCAT(DISTINCT modalidad_es ORDER BY modalidad_es SEPARATOR '\n') as modalidad_es,
GROUP_CONCAT(DISTINCT orgs.nombre_es ORDER BY orgs.nombre_es SEPARATOR '\n') as organizacion_es
FROM tx_oriconvocatorias_publicadas AS pubs

INNER JOIN tx_oriconvocatorias_publicadas_lineas_mm as ml
ON ml.uid_local=pubs.uid

INNER JOIN tx_oritablascomunes_lineas as lins
ON ml.uid_foreign=lins.uid

INNER JOIN tx_oriconvocatorias_publicadas_modalidades_mm as mm
ON mm.uid_local=pubs.uid

INNER JOIN tx_oritablascomunes_modalidades as mods
ON mm.uid_foreign=mods.uid

INNER JOIN tx_oriconvocatorias_publicadas_organizaciones_mm as mo
ON mo.uid_local=pubs.uid

INNER JOIN tx_oritablascomunes_organizaciones as orgs
ON mo.uid_foreign=orgs.uid

INNER JOIN tx_oritablascomunes_paises AS pais
ON pubs.carea = CONCAT('tx_oritablascomunes_paises_',pais.uid)
GROUP BY uid

UNION

SELECT pubs.*, regs.nombre_es as area,
GROUP_CONCAT(DISTINCT linea_es ORDER BY linea_es SEPARATOR '\n') as linea_es,
GROUP_CONCAT(DISTINCT modalidad_es ORDER BY modalidad_es SEPARATOR '\n') as modalidad_es,
GROUP_CONCAT(DISTINCT orgs.nombre_es ORDER BY orgs.nombre_es SEPARATOR '\n') as organizacion_es

FROM tx_oriconvocatorias_publicadas AS pubs

INNER JOIN tx_oriconvocatorias_publicadas_lineas_mm as ml
ON ml.uid_local=pubs.uid

INNER JOIN tx_oritablascomunes_lineas as lins
ON ml.uid_foreign=lins.uid

INNER JOIN tx_oriconvocatorias_publicadas_modalidades_mm as mm
ON mm.uid_local=pubs.uid

INNER JOIN tx_oritablascomunes_modalidades as mods
ON mm.uid_foreign=mods.uid

INNER JOIN tx_oriconvocatorias_publicadas_organizaciones_mm as mo
ON mo.uid_local=pubs.uid

INNER JOIN tx_oritablascomunes_organizaciones as orgs
ON mo.uid_foreign=orgs.uid

INNER JOIN tx_oritablascomunes_regiones AS regs
ON pubs.carea = CONCAT('tx_oritablascomunes_regiones_',regs.uid)
GROUP BY uid

1 个答案:

答案 0 :(得分:0)

是。使用视图收集两个查询共有的所有sql:

CREATE VIEW PUB_ORGS AS
SELECT *
FROM tx_oriconvocatorias_publicadas AS pubs
INNER JOIN tx_oriconvocatorias_publicadas_lineas_mm as ml ON ml.uid_local=pubs.uid
INNER JOIN tx_oritablascomunes_lineas as lins ON ml.uid_foreign=lins.uid
INNER JOIN tx_oriconvocatorias_publicadas_modalidades_mm as mm ON mm.uid_local=pubs.uid
INNER JOIN tx_oritablascomunes_modalidades as mods ON mm.uid_foreign=mods.uid
INNER JOIN tx_oriconvocatorias_publicadas_organizaciones_mm as mo ON mo.uid_local=pubs.uid
INNER JOIN tx_oritablascomunes_organizaciones as orgs ON mo.uid_foreign=orgs.uid;

然后从此

构建联合查询