简单的sql查询
Posted
技术标签:
【中文标题】简单的sql查询【英文标题】:Simple sql query 【发布时间】:2011-04-21 10:07:59 【问题描述】:我有一个关于 SQL 查询的问题。假设我们有:
cinema
name
id_cinema
cinema
city
movies
id_movie
name_movie
假设:
一部电影可以在更多电影院看到; 在电影院你可以看到不同的电影;我有一个类型的表之间的关系:多对多。因此,我需要一个表 cinema-movie
,其中包含主键 id_cinema
id_film
。
是否有一个 sql 查询可以让我拥有电影院中的所有电影?
【问题讨论】:
【参考方案1】:查询将是
select m.* from movies m left join cinema_movie mc on m.id = mc.movie_id where mc.cinema_id = 1;
例如
mysql> select * from movies;
+------+--------+
| id | name |
+------+--------+
| 1 | movie1 |
| 2 | movie2 |
| 3 | movie3 |
| 4 | movie4 |
+------+--------+
4 rows in set (0.00 sec)
mysql> select * from cinema;
+------+-------+---------+
| id | name | cinema |
+------+-------+---------+
| 1 | name1 | cinema1 |
| 2 | name2 | cinema2 |
| 3 | name3 | cinema3 |
| 4 | name4 | cinema4 |
+------+-------+---------+
4 rows in set (0.00 sec)
mysql> select * from cinema_movie;
+----------+-----------+
| movie_id | cinema_id |
+----------+-----------+
| 1 | 1 |
| 3 | 1 |
| 4 | 1 |
| 1 | 3 |
| 3 | 3 |
+----------+-----------+
5 rows in set (0.00 sec)
mysql> select m.* from movies m left join cinema_movie mc on m.id = mc.movie_id where mc.cinema_id = 1;
+------+--------+
| id | name |
+------+--------+
| 1 | movie1 |
| 3 | movie3 |
| 4 | movie4 |
+------+--------+
3 rows in set (0.00 sec)
【讨论】:
left join
对这个 where
子句毫无用处。内部连接就足够了 - 并且会给出相同的结果。【参考方案2】:
显示电影院 10 中的所有电影:
SELECT movies.*
FROM movies
JOIN cinema_movie ON cinema_movie.id_film = movies.id_movie
WHERE cinema_movie.id_cinema = 10
使用这样的JOIN
(内部联接),您可以从movies
中选择并加入cinema_movie
,反之亦然 - 顺序无关紧要。
【讨论】:
【参考方案3】:查询影院信息:
select * from movies as m
join cinema_movie as cm
on m.id_movie = cm.id_movie
join cinema as c
on c.id_cinema = cm.id_cinema
where c.id_cinema = <your id_cinema>
【讨论】:
【参考方案4】:如果你有:
cinema
name
id_cinema
cinema
city
movies
id_movie
name_movie
cinema_movie
id_cinema
id_movie
start_time
然后您可以通过以下方式加入:
SELECT cinema_movies.id_cinema, name, cinema, cinema_movies.id_movie, name_movie
FROM cinema, movies, cinema_movies
WHERE cinema.id_cinema = cinema_movies.id_cinema
AND movies.id_movie = cinema_movies.id_movie
AND cinema_movies.id_cinema = 'northpark12'
【讨论】:
【参考方案5】:如果你想通过cinema.name
搜索:
SELECT cinema.name
, movies.*
FROM movies
INNER JOIN cinema_movie
ON cinema_movie.id_film = movies.id_movie
INNER JOIN cinema
ON cinema_movie.id_cinema = cinema.id_cinema
WHERE cinema.name = "YourCinemaName"
如果你想通过id_cinema
搜索:
SELECT cinema.name
, movies.*
FROM movies
INNER JOIN cinema_movie
ON cinema_movie.id_film = movies.id_movie
INNER JOIN cinema
ON cinema_movie.id_cinema = cinema.id_cinema
WHERE cinema.id_cinema = YourCinemaID
如果你想搜索特定的cinema.id又不想输出cinema的名字,Box9的答案就足够了。
【讨论】:
我使用 Microsoft Access... 你按名称查询我有 sintax 错误... 为什么? (ps:什么是连接类型(内,左...)我可以在 from 运算符之后进行一些连接吗? @GgSalent:您的问题中没有MYSQL
标签吗?如果您使用 Access,请在您的问题中添加该标签。我认为访问也需要INNER JOIN
和/或括号。我会检查的。以上是关于简单的sql查询的主要内容,如果未能解决你的问题,请参考以下文章