Mysql左外连接在我的查询中进行优化

时间:2015-06-13 07:32:54

标签: mysql sql

我有两个名为" tablestr table"的数据库表名。和" restbookingtable":

tablestr:

str_id是主键

enter image description here

restbooking: bookingsection_id是外键

enter image description here

在预订表中我存储str_id多个值,逗号分隔,我的查询是

SELECT `str_id` FROM (`rest_tablestr`) WHERE str_id NOT IN (
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(t.bookingsection_id, ",", n.n), ",", -1) value FROM rest_restaurantbooking t 
CROSS JOIN (
SELECT a.N + b.N * 10 + 1 n FROM (
SELECT 0 AS N
UNION ALL
SELECT 1
UNION ALL
SELECT 2
UNION ALL
SELECT 3
UNION ALL
SELECT 4
UNION ALL
SELECT 5 
UNION ALL 
SELECT 6 
UNION ALL
SELECT 7 
UNION ALL 
SELECT 8 
UNION ALL 
SELECT 9) a , (
SELECT 0 AS N
UNION ALL 
SELECT 1 
UNION ALL 
SELECT 2 
UNION ALL 
SELECT 3 
UNION ALL 
SELECT 4 
UNION ALL 
SELECT 5 
UNION ALL 
SELECT 6 
UNION ALL 
SELECT 7 
UNION ALL 
SELECT 8 
UNION ALL SELECT 9) 
b ORDER BY n ) n 
WHERE n.n <= 1 + (LENGTH(t.bookingsection_id) -
LENGTH(REPLACE(t.bookingsection_id, ",", ""))) AND
t.res_id = 21 AND
t.booking_status not in ("cancelled","departed","noshow") AND
((t.bookingstart_time <= "2015-06-12 19:45:00" AND t.bookingend_time >= "2015-06-12 22:15:00") OR 
(t.bookingend_time >= "2015-06-12 19:45:00" AND t.bookingend_time <= "2015-06-12 22:15:00") OR
(t.bookingstart_time >= "2015-06-12 19:45:00" AND t.bookingstart_time <= "2015-06-12 22:15:00") OR 
(t.bookingstart_time >= "2015-06-12 19:45:00" AND t.bookingend_time <= "2015-06-12 22:15:00")) ) AND
`res_id` = '21' AND
`area_id` = '28' AND 
`wait_table` = 'no' AND
`availability` = 'yes';

结果集:

enter image description here

任何正文都可以帮我用左外连接重写查询,也可以优化查询。

0 个答案:

没有答案