如何在MySQL内连接中排序数据?基于分类排序生成播客播放列表
Alright, let's tackle this problem step by step. You’ve got two core tables to work with—category_sorts (which defines the order of categories) and categories (which holds category details)—and you need to tie these to your podcast data to create a sorted playlist.
First, Recap Your Tables
Here's your category_sorts table (mapping category IDs to their sort order):
SELECT * FROM category_sorts; +----+-------------+------+ | id | category_id | sort | +----+-------------+------+ | 1 | 2 | 1 | | 2 | 1 | 2 | | 3 | 1 | 3 | | 4 | 2 | 4 | +----+-------------+------+
And your categories table (storing category metadata):
SELECT * FROM categories; +----+--------------+-----------+ | id | title | status | +----+--------------+-----------+ | 1 | True Crime | active | | 2 | Tech Reviews | active | +----+--------------+-----------+
(I filled in the truncated categories data with example values for clarity)
Assumptions About Your Podcast Data
I’m assuming you have a podcasts table that links to categories via a category_id column (standard for podcast databases). A simplified version might look like this:
SELECT * FROM podcasts; +----+--------------------------+-------------+ | id | title | category_id | +----+--------------------------+-------------+ | 1 | "Unsolved Case Files" | 1 | | 2 | "Tech Today" | 2 | | 3 | "Murder in the Midwest" | 1 | | 4 | "Future Tech Trends" | 2 | +----+--------------------------+-------------+
SQL Query to Generate Your Sorted Playlist
To create a playlist ordered by the sort value from category_sorts, we’ll join all three tables and sort by that field. We’ll also filter out inactive categories (adjust this if you don’t need it):
SELECT p.title AS podcast_title, c.title AS category_title, cs.sort AS playlist_order FROM podcasts p JOIN category_sorts cs ON p.category_id = cs.category_id JOIN categories c ON cs.category_id = c.id WHERE c.status = 'active' -- Optional: exclude inactive categories ORDER BY cs.sort ASC;
Example Output
Running this query will give you a playlist sorted exactly by the sort values you defined:
+--------------------------+----------------+---------------+ | podcast_title | category_title | playlist_order| +--------------------------+----------------+---------------+ | "Tech Today" | Tech Reviews | 1 | | "Unsolved Case Files" | True Crime | 2 | | "Murder in the Midwest" | True Crime | 3 | | "Future Tech Trends" | Tech Reviews | 4 | +--------------------------+----------------+---------------+
Quick Notes
- If a category has multiple podcasts, they’ll appear in the order of their
sortvalues. Add an extra field to theORDER BYclause (likep.published_date DESCorp.id ASC) if you want to sort podcasts within the same category further. - If you need to include podcasts that don’t have a sort entry, replace
JOIN category_sorts cswithLEFT JOIN category_sorts csto avoid excluding them.
内容的提问来源于stack exchange,提问作者arvernester

