有一个模式,看起来如此:
CREATE TABLE `sys_users` (
`id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
`last_name` varchar(255) NOT NULL,
`available` varchar(1) NOT NULL
) DEFAULT CHARSET=UTF8;
CREATE TABLE IF NOT EXISTS `sys_groups_list` (
`id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL
) DEFAULT CHARSET=UTF8;
CREATE TABLE IF NOT EXISTS `sys_groups_junction` (
`group_id` INT NOT NULL, /* <-- Refers to sys_groups_list.id */
`usr_id` INT NOT NULL /* <-- Refers to sys_users.id */
) DEFAULT CHARSET=UTF8;
在输入时,我有一个id
的某个用户。
在输出时,结果必须如下:
id | last_name | available | group_name
... | ........ | ......... | ..........
我不确定如何正确地编写3 JOIN
来完成此任务,我尝试时最终会出现语法错误。那么你能建议如何正确编写SQL吗?
答案 0 :(得分:2)
SELECT sys_users.id, lastname, available, sys_groups_list.name
FROM sys_users
JOIN sys_groups_junction
ON sys_users.id = sys_groups_junction.usr_id
JOIN sys_groups_list
ON sys_groups_junction.group_id = sys_groups_list.id