0

所以我对这个查询有疑问

SELECT e.entreprise, e.entreid, e.chargee, e.date, e.tel, e.email, e.adresse, e.ville,
e.codepostal, e.fax, e.accronyme, GROUP_CONCAT(c.nom, c.prenom, c.email separator ',') as keywords 
FROM contacts as c
LEFT JOIN entreprise as e ON e.entreid=c.contactid
LEFT JOIN metas as m ON e.entreid=m.elem_id
WHERE  e.entreid !=1 AND e.actif!='inactif' 
     AND ((m.meta_key='type_entreprise' 
     AND m.meta_value REGEXP '(client)') 
     OR m.meta_key is null) 
GROUP BY e.entreid  ORDER BY e.entreprise ASC

这个查询是假设返回给我所有的客户企业......问题是使它成为客户的字段在元表中(像 9000 个条目和许多用于企业),当我运行这个查询时它需要大约 70 秒来执行它。

如果有人可以提供帮助,将不胜感激

4

2 回答 2

0

好的,所以使用cars10 的评论,我已经能够将查询时间从70 秒减少到2.2 秒。我不知道这是否是正确的做法,但它似乎有效。

这是新的查询

CREATE TEMPORARY TABLE temptable AS (SELECT m.meta_value, m.elem_id FROM metas as m WHERE m.meta_key='type_entreprise');
SELECT e.entreprise, e.entreid, e.chargee, e.date, e.tel, e.email, e.adresse, e.ville,     e.codepostal, e.fax, e.accronyme, GROUP_CONCAT( c.nom, c.prenom, c.email
SEPARATOR ',' ) AS keywords, temp.meta_value
FROM contacts AS c
LEFT JOIN entreprise AS e ON e.entreid = c.contactid
LEFT JOIN temptable AS temp ON temp.elem_id = e.entreid
WHERE e.entreid !=1
AND e.actif != 'inactif'
AND temp.meta_value REGEXP "(client)"
GROUP BY e.entreid
ORDER BY e.entreprise ASC
于 2013-07-31T14:51:00.453 回答
0

查看您的解释,它没有使用元表上的任何索引。

在 2 列上尝试复合键,meta_key 和 elem_id

至于查询,试试这样: -

SELECT e.entreprise, e.entreid, e.chargee, e.date, e.tel, e.email, e.adresse, e.ville,
e.codepostal, e.fax, e.accronyme, GROUP_CONCAT(c.nom, c.prenom, c.email separator ',') as keywords 
FROM contacts as c
LEFT JOIN entreprise as e 
ON e.entreid = c.contactid
LEFT JOIN metas as m 
ON e.entreid = m.elem_id
AND m.meta_key = 'type_entreprise' 
AND m.meta_value REGEXP '(client)' 
WHERE e.entreid !=1 
AND e.actif!='inactif' 
GROUP BY e.entreid  
ORDER BY e.entreprise ASC

鉴于您带回的大多数字段都来自该表,因此看起来对企业进行 LEFT JOIN 似乎不合逻辑。如果您必须始终拥有有关 entreprise 的记录,则将其更改为 INNER JOIN ,这应该允许它使用该索引,然后从那里到联系人:-

SELECT e.entreprise, e.entreid, e.chargee, e.date, e.tel, e.email, e.adresse, e.ville,
e.codepostal, e.fax, e.accronyme, GROUP_CONCAT(c.nom, c.prenom, c.email separator ',') as keywords 
FROM entreprise as e 
INNER JOIN contacts as c
ON e.entreid = c.contactid
LEFT JOIN metas as m 
ON e.entreid = m.elem_id
AND m.meta_key = 'type_entreprise' 
AND m.meta_value REGEXP '(client)' 
WHERE e.entreid !=1 
AND e.actif!='inactif' 
GROUP BY e.entreid  
ORDER BY e.entreprise ASC
于 2013-07-30T15:31:05.343 回答