我一直在測試SQL查詢以尋求從列'車隊','行程','預訂','代理商'和'人員'獲取數據的查詢。SQL查詢花費時間過長(LEFT OUTER JOIN)
問題是這個查詢花了很長時間(2分鐘)才能完成。 我嘗試使用'WHERE'和/或'INNER JOIN',查詢時間縮短到幾毫秒,但它並沒有給我所有我想要的結果。例如,「旅行」中有一些條目沒有「預訂」關聯或某些「預訂」條目沒有「人員」關聯。這就是爲什麼我需要使用LEFT OUTER JOIN,但這使得查詢非常緩慢。
我相信我在這個語法中有一些效率問題,但我無法弄清楚它是什麼。
我想要的結果是這樣的:
bid tid tstatus timestamp start end gname pname fname blockedtrips tcreator bcreator baname taname
NULL 2736 1 1468022400 540 720 NULL NULL Little Boy 1 9 NULL NULL Conscience Dauphin
NULL 2737 1 1468022400 540 720 NULL NULL Moby Dick 1 9 NULL NULL Conscience Dauphin
我的查詢如下:
SELECT
bookings.id AS bid, trips.id AS tid, trips.id_status AS tstatus,
trips.timestamp, trips.start, trips.end, bookings.groupname AS gname,
persons.name AS pname, fleet.name AS fname, trips.blockedtrips AS blockedtrips,
trips.id_creator AS tcreator, bookings.id_creator AS bcreator,
(SELECT name FROM agencies WHERE deleted=false AND id=bookings.id_agency) AS baname,
(SELECT name FROM agencies WHERE deleted=false AND id=trips.id_agency) AS taname
FROM
trips OUTER LEFT JOIN fleet ON fleet.id = trips.id_fleet AND fleet.deleted=false AND trips.deleted=false
LEFT OUTER JOIN bookings ON trips.id = bookings.id_trip AND bookings.deleted=false
LEFT OUTER JOIN persons ON bookings.id = persons.id_booking AND persons.deleted=false
AND (
(SELECT name FROM agencies WHERE deleted=false AND id=bookings.id_agency) LIKE '%conscience%'
OR (SELECT name FROM agencies WHERE deleted=false AND id=trips.id_agency) LIKE '%conscience%'
OR bookings.groupname LIKE '%conscience%'
OR persons.name LIKE '%conscience%'
OR fleet.name LIKE '%conscience%'
)
ORDER BY trips.timestamp
DESC LIMIT 0,100
查詢而更新:
SELECT
bookings.id AS bid, trips.id AS tid, trips.id_status AS tstatus,
trips.timestamp, trips.start, trips.end, bookings.groupname AS gname,
persons.name AS pname, fleet.name AS fname, trips.blockedtrips AS blockedtrips,
trips.id_creator AS tcreator, bookings.id_creator AS bcreator,
bagency.name AS baname, tagency.name AS taname
FROM fleet
LEFT JOIN trips ON fleet.id = trips.id_fleet AND fleet.deleted=false AND trips.deleted=false
LEFT JOIN agencies AS tagency ON tagency.id = trips.id_agency AND tagency.deleted=false
LEFT JOIN bookings ON trips.id = bookings.id_trip AND bookings.deleted=false
LEFT JOIN agencies AS bagency ON bagency.id = bookings.id_agency AND bagency.deleted=false
LEFT JOIN persons ON bookings.id = persons.id_booking AND persons.deleted=false
WHERE
bagency.name LIKE '%conscience%'
OR tagency.name LIKE '%conscience%'
OR bookings.groupname LIKE '%conscience%'
OR persons.name LIKE '%conscience%'
OR fleet.name LIKE '%conscience%'
ORDER BY trips.timestamp DESC
LIMIT 0,100
這是用於mysql還是sql-server?請使用適當的標籤 – ughai 2015-04-03 07:25:54
我的錯誤。這是mySQL – user2084401 2015-04-03 08:00:31