I am using a query which gives result within a second.
The query is,
SELECT creator.first_name, image.id, image.image_code, image.project, image.location, image.image_date, image.image_view, image.copyright
FROM img_images image, img_creator creator
WHERE creator.image_id = image.id AND (
(image.image_code LIKE '%text%')
OR (image.project LIKE '%text%')
OR (image.location LIKE '%text%')
OR (creator.first_name LIKE '%text%'))
ORDER BY creator.first_name
Now if I add third table in this query, it takes about 20 to 30 seconds to give results.
Query,
SELECT creator.first_name, image.id, image.image_code, image.project, image.location, image.image_date, image.image_view, image.copyright, sources.author
FROM img_images image, img_creator creator, img_source sources
WHERE creator.image_id = image.id AND sources.image_id = image.id AND (
(image.image_code LIKE '%text%')
OR (image.project LIKE '%text%')
OR (image.location LIKE '%text%')
OR (creator.first_name LIKE '%text%'))
ORDER BY creator.first_name
How can I optimize this query to give response quickly? Proper indexing is present in all tables.
Sometimes forcing a left join on a table that has no filtering conditions helps the RDBMS select a better plan:
SELECT creator.first_name, image.id, image.image_code, image.project, image.location,
image.image_date, image.image_view, image.copyright, sources.author
FROM img_images image
JOIN img_creator creator ON (creator.image_id = image.id OR creator.first_name LIKE '%text%')
LEFT JOIN img_source sources ON (sources.image_id = image.id)
WHERE image.image_code LIKE '%text%' OR image.project LIKE '%text%' OR image.location LIKE '%text%'
ORDER BY creator.first_name;
Also, when the number of rows in the resultset are expected to be small, but the query is complex and/or involves large tables, I find worthwhile trying individual lookups for single values:
SELECT creator.first_name, image.id, image.image_code, image.project, image.location,
image.image_date, image.image_view, image.copyright
(SELECT author FROM img_source WHERE image_id = image.id) AS author
FROM img_images image
JOIN img_creator creator ON (creator.image_id = image.id OR creator.first_name LIKE '%text%')
WHERE image.image_code LIKE '%text%' OR image.project LIKE '%text%' OR image.location LIKE '%text%'
ORDER BY creator.first_name;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.