我有3张桌子
TABLE #1 "users"
3 columns
User-ID int (11)
Location varchar (250)
Age int (11)
Primary-key (User-ID)
TABLE #2 "books"
5 columns
ISBN varchar (13)
Book-title varchar(255)
Book-author varchar (255)
Year-of-publication int(10)
Publisher varchar (255)
TABLE #3 "Book-raitings"
3 columns
User-ID int (11)
ISBN varchar (13)
Book-rating int (11)
Primary-key (user-id, ISBN)
位置列varchar
的格式为(city, state, country
)
我必须将每个国家的前10本书生成一个单独的表格。生成SQL转储。
提前感谢您的帮助。
答案 0 :(得分:0)
一些初步建议:
'Book-ratings'
。'Book-rating'
而不是:Book_ratings.Book_rating
符号减号是MySql中的运算符。您可以通过这种方式创建一个国家/地区的表格:
CREATE TABLE books_by_country
SELECT
`Book-ratings`.`Book-rating`,
`books`.`Book-title`,
REPLACE(`users`.`Location`,CONCAT(SUBSTRING_INDEX(`users`.`Location`, ',', 2),', '),'') as Country
FROM `Book-ratings`
LEFT JOIN `books` ON `books`.`ISBN` = `Book-ratings`.`ISBN`
LEFT JOIN `users` ON `Book-ratings`.`User-ID` = `Book-ratings`.`User-ID`;
通过这种方式,您可以通过这种方式为每个国家/地区挑选前10本书:
SELECT
`books_by_country`.`Country`,
`books_by_country`.`Book-title`,
SUM(`books_by_country`.`Book-rating`) as Book_ranking
FROM `Test`.`books_by_country`
WHERE `books_by_country`.`Country`= 'USA'
Group BY `books_by_country`.`Country`,`books_by_country`.`Book-title`
ORDER BY Book_ranking DESC
LIMIT 10;
此致