-1

我有一个名为库的数据库。有作者、书籍、books_genres、流派、历史

我还有 5 本书类型为“恐怖”,3 本书类型为“喜剧”,2 本书类型为“浪漫”

我有一个包含我所有流派的复选框,当我选择它们时,我希望将结果按流派分组,大多数记录在 TOP 上。这是一些代码:

"SELECT title, price, genre_id, name
FROM books
INNER JOIN books_genres ON books.id = books_genres.book_id
INNER JOIN genres ON books_genres.genre_id = genres.id
WHERE genre_id IN ({$ids})";

这将所有书籍归还给我,但没有我想要的顺序。

ids 是流派 id 的字符串,如 1,2,3,4

4

2 回答 2

3

使用MYSQLORDER BY ,如下所示:

SELECT ... FROM .... WHERE ... ORDER BY id DESC

DESC用于降序/ASC用于升序

编辑:试试这个:

"SELECT title, price, genre_id, name, (SELECT COUNT(*) FROM books_genres as b WHERE b.genre_id = genres.id) as genreCount
FROM books
INNER JOIN books_genres ON books.id = books_genres.book_id
INNER JOIN genres ON books_genres.genre_id = genres.id
WHERE genre_id IN ({$ids})
ORDER BY genreCount DESC, genres.id ASC;"
于 2013-06-26T22:04:02.217 回答
1

您使用子查询和 ORDER BY 子句。

例如:

"SELECT title, price, genre_id, name, (SELECT count(*) FROM books AS bks WHERE bks.genre_id = books.genre_id) AS genre_count
FROM books
INNER JOIN books_genres ON books.id = books_genres.book_id
INNER JOIN genres ON books_genres.genre_id = genres.id
WHERE genre_id IN ({$ids})
ORDER BY genre_count DESC"
于 2013-06-26T22:08:20.217 回答