我已经搜索并查看了很多关于mySQL的不同join和union命令,但找不到关于代码底层问题的解决方案。
我只使用mySQL几天试图学习mySQL,HTML,CSS,PHP,javascript,python等,以创建我自己的数据库,网页,备份服务器,使我的家庭互联等等。非常感谢帮助! '塔克'提前! :)
create database cinema;
use cinema;
create table cinema.genre (
genre_code varchar(3) not null,
genre varchar(45) null,
primary key (genre_code) );
create table cinema.movie (
movie_id int not null auto_increment,
genre varchar(3) null,
released int(4) null,
title varchar(45) not null,
name_director varchar(45) null,
primary key(movie_id),
constraint FK_genre foreign key (genre) references cinema.genre(genre_code) );
create table movie_halls (
hall_id int not null auto_increment,
hall_name varchar(45) not null,
spaces int not null,
primary key (hall_id) );
create table overview (
cinema_per_id int not null auto_increment,
date_time datetime not null, #1000-01-01 00:00:00
hall_id int not null,
movie_id int not null,
number_people int null,
primary key (cinema_per_id) );
insert into cinema.genre values
('COM', 'Comedy'),
('ACT', 'Action'),
('DRA', 'Drama'),
('HOR', 'Horror');
insert into cinema.movie (genre, released, title, name_director) values
('COM', 2010, '2 goats', 'Speilberg, Peter'),
('ACT', 2012, 'Fast5', 'Dramaqueen'),
('DRA', 1995, 'Status quo', 'Turtle, Ninja'),
('ACT', 1950, 'Joker', 'Man, Spider');
insert into movie_halls (hall_name, spaces) values
('Darth Vader', 200),
('Princess Leila', 150),
('Yoda', 1999),
('Obi-Wan Kenobi', 1920);
这就是我想要输入概述的内容(为了方便而不记住电影和大厅的所有内容。
insert into overview (date_time, hall_id, movie_id, number_people) values
(2018-04-06 20:00:00, 'Darth Vader', 'Fast5', 120),
(2018-04-06 20:00:00, 'Yoda', 'Joker', 1500),
(2018-04-06 21:30:00, 'Obi-Wan Kenobi', '2 goats', 1200);
如果我现在在插入后选择概述,我希望看到以下内容(不要介意日期时间格式 - 只需将其混合起来):
我不确定这是否可行,或者我的数据库的一般建模是否有问题。非常感谢任何澄清和帮助!
答案 0 :(得分:0)
作为变体,您可以使用子查询插入
insert into overview (date_time, hall_id, movie_id, number_people) values
('2018-04-06 20:00:00', (select hall_id from movie_halls where hall_name='Darth Vader'), (select movie_id from movie where title='Fast5'), 120),
('2018-04-06 20:00:00', (select hall_id from movie_halls where hall_name='Yoda'), (select movie_id from movie where title='Joker'), 1500),
('2018-04-06 21:30:00', (select hall_id from movie_halls where hall_name='Obi-Wan Kenobi'), (select movie_id from movie where title='2 goats'), 1200)
然后使用JOIN
的查询。例如
SELECT
o.*,
h.hall_name,
m.title AS movie_title
FROM overview o
JOIN movie_halls h ON o.hall_id=h.hall_id
JOIN movie m ON o.movie_id=m.movie_id
ORDER BY o.date_time