所以基本上我有3个表:学生,班级和入学人数。
CREATE TABLE class
(`class_name` varchar(13), `class_id` int primary key)
;
INSERT INTO class
(`class_name`, `class_id`)
VALUES
('math', 5697),
('science', 5768),
('computer', 6315),
('physical-ed', 6422),
('music', 7528),
('art', 7604),
('jrotc', 8797),
('culinary-arts', 8069)
;
CREATE TABLE student
(`student_fname` varchar(8), `student_id` varchar(11) primary key)
;
INSERT INTO student
(`student_fname`, `student_id`)
VALUES
('james', 'Vre94b3JpXO'),
('jim', 'JzqQ2zRVNm1'),
('jenny', 'xgqv9P42eYL'),
('kyle', 'QLNM0Wbyqk0'),
('kimberly', 'P2egAddWN0Q'),
('kayla', 'EGNDjWAreAy'),
('noah', 'bPeOyMMONGr'),
('nataly', '9Op53GGmqk5')
;
create table enrollment (
`no` int(10),
`student_id` varchar(11),
`class_id` int,
`semester` varchar(20),
primary key (`student_id`, `class_id`, `semester`),
foreign key (`student_id`) references student (`student_id`),
foreign key (`class_id`) references class (`class_id`)
);
insert into enrollment values
(1, 'Vre94b3JpXO', 5697, 'Fall 2015'),
(2,'JzqQ2zRVNm1', 5697, 'Fall 2015'),
(3, 'xgqv9P42eYL', 5697, 'Fall 2015'),
(4, 'JzqQ2zRVNm1', 8069, 'Fall 2014'),
(5, 'xgqv9P42eYL', 8069, 'Fall 2014');
如果我遵循以下查询:
select * from student s
join enrollment e on s.student_id = e.student_id
join class c on c.class_id = e.class_id
如何删除诸如student_id和class_id之类的多余列?
此问题从页面扩展: Table structure - Link one student with multiple classes id
和demo
我一直在使用加入方法,但由于您的帮助,我无法获得想要的东西。
答案 0 :(得分:3)
要回答这个问题,最好回顾一下一些基础知识:
SELECT *
此*
将显示所选表中的所有列
如果只想显示一些列,则必须专门命名:
SELECT class_name, ...
但是,如果某些表具有相同的列名,则必须指定表名或别名:
SELECT c.class_name
FROM mytable t
INNER JOIN class c ON c.id_table = t.id
答案 1 :(得分:1)
类似这样的东西:
SELECT s.*
,e.no
,e.class_id
,e.semester
,c.class_name
FROM student s
INNER JOIN enrollment e ON s.student_id = e.student_id
INNER JOIN class c ON c.class_id = e.class_id
根据您的选择,您可以指定所需的每一列,以及顺序。
SELECT e.no
,e.class_id
如果您要从表中获取所有列,则可以使用该表的点星,例如:
SELECT s.*
就像您在现有查询中已经拥有的那样,您只需简单地加星号即可获取所有列:
SELECT *
这里是一些基本的SELECT
技巧的起点:https://www.techrepublic.com/article/sql-basics-select-statement-options/
顺便说一句,使用类似http://poorsql.com/的网站来帮助您进行SQL格式化会很有帮助。
答案 2 :(得分:0)
只需指定要查看的列即可。
select s.student_fname, s.student_id,
e.no, e.class_id, e.semester,
c.class_name,
from
student s join enrollment e
on s.student_id = e.student_id
join class c
on c.class_id = e.class_id ;