[英]PHP MySQL Combining 2 queries
Table genre 表格类型
id | genre | display
---+-----------+------------
1 | Action | 1
2 | Comedy | 0
3 | Romance | 1
Table movies 表电影
id | genre_id | movie | year | display
---+-----------+---------------+---------+------------
1 | 1 | Kill Bill | 2003 | 1
2 | 1 | Die Hard | 1988 | 0
3 | 2 | Anchorman | 2004 | 1
4 | 3 | Titanic | 1997 | 1
5 | 3 | Casablanca | 1942 | 1
Query 询问
SELECT genre.genre, movies.movie, movies.year FROM `genre` JOIN `movies` ON
genre.id = movies.genre_id WHERE genre.display = 1 AND movies.display = 1
I'm trying to write a sql statement so that I get the result below in this specific order. 我正在尝试编写一个sql语句,以便我按照这个特定的顺序得到下面的结果。 If a genre has a display of 1, then the genre itself will be displayed, as well as any of its movies that have a display of 1. Also, genre names shouldn't be duplicated:
如果一个类型的显示为1,则将显示该类型本身,以及显示为1的任何电影。此外,不应重复类型名称:
Action 行动
Romance 浪漫
Your query selects the right rows. 您的查询选择正确的行。 I think the only issue is the ordering:
我认为唯一的问题是订购:
SELECT genre.genre, movies.movie, movies.year
FROM `genre` JOIN
`movies`
ON genre.id = movies.genre_id
WHERE genre.display = 1 AND movies.display = 1
order by genre.genre, movies.year desc;
If you don't want the genre to duplicate, you can use a funky trick. 如果你不想复制类型,你可以使用一个时髦的技巧。 That is,
union
the genres in with NULL
movies, then order them correctly and remember to remove the names after that: 也就是说,
union
与流派NULL
电影,然后正确排序并记住后,除去名称:
select (case when movie is NULL then genre else NULL end) as genre,
movie, year
from ((select genre, NULL as movie, NULL as year
from genre
where display = 1
) union all
(SELECT genre.genre, movies.movie, movies.year
FROM `genre` JOIN
`movies`
ON genre.id = movies.genre_id
WHERE genre.display = 1 AND movies.display = 1
)
) t
order by genre,
movie is null desc,
year desc
Normally, I would say to do this in the app layer, but it can be fun to put together the SQL for something like this. 通常,我会说在app层中执行此操作,但将SQL放在一起可能很有趣。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.