我正在尝试在我的数据库中的字段中搜索相同的文本以获取实时搜索框。
SELECT DISTINCT u.id, u.username FROM
users AS u, user_invoice AS ui, user_roles AS ur, roles AS r WHERE
u.id = ur.user_id AND
ur.role_id = r.id AND
r.name = 'teacher' AND
(
ui.user_id = u.id AND
CAST(ui.invoice AS TEXT) = 'searchterm'
)
此查询搜索发票表并以极快的速度正确返回结果。
SELECT DISTINCT u.id, u.username FROM
users AS u, user_invoice AS ui, user_roles AS ur, roles AS r WHERE
u.id = ur.user_id AND
ur.role_id = r.id AND
r.name = 'teacher' AND
(u.username like '%searchterm%')
此查询搜索匹配的用户名并且返回速度也非常快。
但是当我像这样将两者结合起来时:
SELECT DISTINCT u.id, u.username FROM
users AS u, user_invoice AS ui, user_roles AS ur, roles AS r WHERE
u.id = ur.user_id AND
ur.role_id = r.id AND
r.name = 'teacher' AND
(
u.username like '%searchterm%' OR
(
ui.user_id = u.id AND
CAST(ui.invoice AS TEXT) = 'searchterm'
)
)
它返回正确的结果,但需要将近一分钟。我究竟做错了什么?
编辑:解释我的查询:
首先: http ://explain.depesz.com/s/PvS
第二: http ://explain.depesz.com/s/D5c
合并: http ://explain.depesz.com/s/Dhf
因复制铸造线时出现错误而进行了编辑。