SELECT orcamentos.id
FROM usuarios, clientes, empresas, orcamentos
WHERE
(
(
clientes.nome LIKE '%VARIAVEL%'
AND clientes.email=usuarios.usuario
)
AND orcamentos.cliente=usuarios.id
)
OR
(
(
(
empresas.razao_social LIKE '%VARIAVEL%'
OR empresas.nome_fantasia LIKE '%VARIAVEL%'
)
AND empresas.email=usuarios.usuario
)
AND orcamentos.cliente=usuarios.id
)
OR orcamentos.nome_cliente LIKE '%VARIAVEL%'
GROUP BY orcamentos.id;
我的这个查询可以正常工作,但存在性能问题。我想要一些查询结构的技巧来优化这个,比如:在这种情况下最好是 join
等。SGBD 是 mysql。
谢谢。
最佳答案
我认为这个查询更清楚:
SELECT orcamentos.id
FROM usuarios
join orcamentos on orcamentos.cliente=usuarios.id
left join clientes on clientes.email=usuarios.usuario
left join empresas on empresas.email=usuarios.usuario
WHERE
COALESCE(clientes.nome,'') + COALESCE(empresas.razao_social,'') +
COALESCE(empresas.nome_fantasia,'') + orcamentos.nome_cliente LIKE '%VARIAVEL%'
GROUP BY orcamentos.id;
请注意哪些是左连接,您也可以将 orcamentos 设为左连接,但这样您的结果集中就会有一行为 null。
您仍然会遇到性能问题。像 clientes.nome LIKE '%VARIAVEL%'
这样的搜索很慢,因为无法使用索引。某些 SQL 平台具有 CONTAINS 关键字,但速度仍然很慢,除非您使用的产品具有全文搜索功能并且已为正在搜索的列启用它。需要全表扫描才能在字段中查找任意字符串。索引要快得多。
如果您总是搜索相同的东西,可以使用一些技巧来加快搜索速度。
关于mysql - sql查询性能不佳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24998295/