【发布时间】:2018-03-01 10:56:00
【问题描述】:
我有3张桌子如下 医生
CREATE TABLE `doctors` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`first_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`last_name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`phone_number` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`avatar_path` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`qualification` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`status` tinyint(4) NOT NULL DEFAULT '0',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `doctors_email_unique` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
专业
CREATE TABLE `specializations` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`status` tinyint(4) NOT NULL DEFAULT '0',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=105 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
以及这两张表中的多对多
CREATE TABLE `doctor_specialization` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`doctor_id` int(10) unsigned NOT NULL,
`specialization_id` int(10) unsigned NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `doctor_specialization_doctor_id_foreign` (`doctor_id`),
KEY `doctor_specialization_specialization_id_foreign` (`specialization_id`),
CONSTRAINT `doctor_specialization_doctor_id_foreign` FOREIGN KEY (`doctor_id`) REFERENCES `doctors` (`id`),
CONSTRAINT `doctor_specialization_specialization_id_foreign` FOREIGN KEY (`specialization_id`) REFERENCES `specializations` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
现在我希望查询从医生那里得到结果,如果超过 1,则用逗号分隔。
有什么办法可以用mysql的方式实现吗?或者我必须对每个结果集执行php loops?
【问题讨论】:
-
GROUP_CONCAT(专业化)...
标签: mysql query-optimization inner-join resultset