CREATE TABLE `rest_profile` ( `id` int(11) NOT NULL, `title` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `description` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `city` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `address` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `rating` int(5) NOT NULL, `owner` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; CREATE TABLE `rest_tables` ( `id` int(11) NOT NULL, `rest_profile_id` int(11) NOT NULL, `capacity` int(11) NOT NULL, `time_start` time NOT NULL, `time_end` time NOT NULL, `disabled` smallint(2) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; INSERT INTO `rest_profile` (`id`, `title`, `description`, `city`, `address`, `rating`, `owner`) VALUES (1, 'Dunkin Donuts', 'Floating-point types represent numbers with fractional parts. Kotlin has two such types: Double (64 bits) and Float (32 bits). ', 'Moscow', '', 0, ''); INSERT INTO `rest_tables` (`id`, `rest_profile_id`, `capacity`, `time_start`, `time_end`, `disabled`) VALUES (1, 1, 4, '11:00:00', '15:00:00', 0), (2, 1, 4, '11:30:00', '15:00:00', 0); SELECT rest.id, rest.title, rest.description, SUM(tbl.capacity) as cap FROM rest_tables as tbl JOIN rest_profile rest ON rest.id = tbl.rest_profile_id WHERE time_start <= '12:00:00' AND time_end >= '13:00:00' GROUP BY 1,2,3 HAVING cap >= 6