在创建本地电影数据库时,我有3个具有以下结构的表:
TABLE1: movies
movie_id | movie_title
TABLE2: categories
category_id | category_title
TABLE3: categories_movies
id | movie_id | category id
1部电影可以有多个类别,我试图用其类别显示每部电影,例如:
MOVIE TITLE 1 (Category 1, Category 2, Category 3)
MOVIE TITLE 2 (Category 2, Category 3)
目前我使用3个查询,首先选择所有电影:
select * from movies
然后
select * from categories_movies where movie_id = $movie_id
然后
select * from categories where category_id = $category_id
我已经测试了一些内部联接,但没有好主意,因为1部电影可以有多个类别。
任何建议都会有所帮助,谢谢。
答案 0 :(得分:2)
我并不完全了解您要显示的格式是什么,但如果要将其显示为1列,则可以使用GROUP_CONCAT()
:
SELECT m.movie_title,GROUP_CONCAT(c.category_title)
FROM movies m
INNER JOIN categories_movies cm
ON m.movie_id = cm.movie_id
INNER JOIN categories c
ON cm.category_id = c.category_id
GROUP BY m.movie_title
如果您只是希望它们显示为单独的行:
SELECT m.movie_title,c.category_title
FROM movies m
INNER JOIN categories_movies cm
ON m.movie_id = cm.movie_id
INNER JOIN categories c
ON cm.category_id = c.category_id
答案 1 :(得分:1)
我认为您需要使用左连接:
SELECT m.movie_title,c.category_title
FROM movies m
LEFT JOIN categories_movies cm
ON m.movie_id = cm.movie_id
LEFT JOIN categories c
ON cm.category_id = c.category_id
答案 2 :(得分:1)
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
// local declarations
int len;
char* pStr;
// statements
printf(" how many characters you want to enter?\n");
scanf("%d", &len);
pStr=(char*)calloc(len+1,sizeof(char));
printf("\n enter your string: ");
gets(pStr);
*(pStr+len)='\0';
printf("\n your string: ");
puts(pStr);
printf(" oops! last character deleted.");
getch();
return 0;
}
答案 3 :(得分:0)
你可以使用GROUP_CONCAT()。它完美无缺:
SELECT movies.movie_title, GROUP_CONCAT( categories.category_title )
FROM movies
INNER JOIN categories_movies ON movies.movie_id = categories_movies.movie_id
INNER JOIN categories ON categories_movies.category_id = categories.category_id
GROUP BY movies.movie_title;