2014-05-06 3 views
-2

У меня есть четыре стола, таблица художников, музыкальный стол, таблица покупки музыки и таблица покупки альбома, как показано ниже;MySQL Присоединиться к нескольким таблицам и отсортировать по популярности

В основном, я хочу получить самый популярный артист, основанный на покупках музыки (покупка таблицы) и покупках альбомов (purchase_albums). любая помощь здесь будет оценена.

художник

id name  
17 Rabadaba 
23 Patrobas Abille 
24 Pryce 

музыка

id song_title artist_id album_id 
30 Intro   17  15 
38 Oli Mubi   17  15 
52 Bwekiri   23  15 

покупки (музыка покупки таблица)

id music_id member_id  
1 30    7  
2 38    7  
3 52    7  

purchased_albums

id album_id member_id 
1  15   7  

здесь схемы базы данных

CREATE TABLE IF NOT EXISTS `albums` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `name` text NOT NULL, 
    `artist_id` int(11) NOT NULL, 
    `date` datetime NOT NULL, 
    `price` int(11) NOT NULL, 
    `pic_location` text NOT NULL, 
    `spinapp_cut` float NOT NULL, 
    PRIMARY KEY (`id`) 
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=16 ; 

-- 
-- Dumping data for table `albums` 
-- 

INSERT INTO `albums` (`id`, `name`, `artist_id`, `date`, `price`, `pic_location`, `spinapp_cut`) VALUES 
(15, 'Musanvu Kitundu', 17, '2014-04-30 05:15:46', 12000, 'uploads/p18mor8nof4u9jmn1jarqem1t5o5.jpg/', 2000); 
CREATE TABLE IF NOT EXISTS `artists` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `name` text NOT NULL, 
    `date_posted` datetime NOT NULL, 
    `pic_location` text NOT NULL, 
    `website` text NOT NULL, 
    `press_contact` text NOT NULL, 
    `bio` text NOT NULL, 
    `country` text NOT NULL, 
    `artist_percentage` float NOT NULL, 
    PRIMARY KEY (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=25 ; 

INSERT INTO `artists` (`id`, `name`, `date_posted`, `pic_location`, `website`, `press_contact`, `bio`, `country`, `artist_percentage`) VALUES 
(17, 'Rabadaba', '2014-04-30 05:10:09', 'uploads/p18moquhh918llbht17br1lbuig65.jpg/', '', '', 'Rabadaba, real names Ss real"', 'Uganda', 50), 
(23, 'Patrobas Abille', '2014-05-05 08:14:04', 'uploads/p18n61g63h1imj1h7g1bmt2o7jr85.png/', '', '', 'About DUSTVILLE & CRANE GANG AMBASSADOR CALL ME THE DUST TRAFFICKER DA\n', 'Uganda', 40), 
(24, 'Pryce', '2014-05-05 08:42:03', 'uploads/p18n631uoi10ogsrrp61mso196o5.jpg/', 'n/a', 'n/a', 'n/a', 'Uganda', 40); 

CREATE TABLE IF NOT EXISTS `music` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `song_title` text NOT NULL, 
    `file_size` int(11) NOT NULL, 
    `artist_id` int(11) NOT NULL, 
    `date_posted` datetime NOT NULL, 
    `hashed_file_location` text NOT NULL, 
    `in_featured` int(11) NOT NULL, 
    `album_id` int(11) NOT NULL, 
    PRIMARY KEY (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=62 ; 

INSERT INTO `music` (`id`, `song_title`, `file_size`, `artist_id`, `date_posted`, `hashed_file_location`, `in_featured`, `album_id`) VALUES 
(27, 'Side Dish ft Cindy', 4896804, 17, '2014-04-30 06:02:21', 'uploads/p18motu3jt1s7k10r53rkasnqc65.mp3/', 0, 15), 
(28, 'Yegwe ft Gatimo', 4544161, 17, '2014-04-30 06:03:16', 'uploads/p18motvqu9l09vu41n5h88huvp5.mp3/', 0, 15), 
(29, 'Byanema ft Gatimo', 4477129, 17, '2014-04-30 06:04:08', 'uploads/p18mou1duo1nma1ealkdk571po85.mp3/', 0, 15), 
(30, 'We Done ft Atlas da African', 4770033, 17, '2014-04-30 06:05:28', 'uploads/p18mou3oku1cv5ai8brgn4r87k5.mp3/', 0, 15), 
(36, 'Okoona Mu', 3110008, 17, '2014-04-30 06:39:52', 'uploads/p18mp02v3v1a8pnatmj31jka1q6t5.mp3/', 0, 0), 
(37, 'Tonsobola', 3879091, 17, '2014-04-30 06:40:51', 'uploads/p18mp04ck3kc861i7teidd1rj15.mp3/', 0, 0), 
(38, 'Love Portion', 4486276, 17, '2014-04-30 06:41:31', 'uploads/p18mp05m1r116rrk11inbthroff5.mp3/', 1, 0), 
(51, 'We Are', 4515443, 23, '2014-05-05 08:23:45', 'uploads/p18n620b5e1qr118ui1mcj1am0tmb5.mp3/', 0, 0), 
(52, '256', 3679294, 23, '2014-05-05 08:37:46', 'uploads/p18n62pur24471h9o13hk115g11dm5.mp3/', 1, 0), 


CREATE TABLE IF NOT EXISTS `purchased_albums` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `album_id` int(11) NOT NULL, 
    `member_id` int(11) NOT NULL, 
    `date` datetime NOT NULL, 
    `ac` float NOT NULL, 
    `sc` float NOT NULL, 
    `paid` int(11) NOT NULL, 
    PRIMARY KEY (`id`) 
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; 

INSERT INTO `purchased_albums` (`id`, `album_id`, `member_id`, `date`, `ac`, `sc`, `paid`) VALUES 
(1, 15, 7, '2014-05-05 15:52:17', 10000, 2000, 0); 

CREATE TABLE IF NOT EXISTS `purchases` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `music_id` int(11) NOT NULL, 
    `member_id` int(11) NOT NULL, 
    `date` datetime NOT NULL, 
    `artist_cut` float NOT NULL, 
    `spinapp_cut` float NOT NULL, 
    `paid` int(11) NOT NULL, 
    PRIMARY KEY (`id`) 
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ; 

INSERT INTO `purchases` (`id`, `music_id`, `member_id`, `date`, `artist_cut`, `spinapp_cut`, `paid`) VALUES 
(1, 30, 7, '2014-04-30 06:20:42', 450, 450, 0), 
(2, 38, 7, '2014-04-30 09:56:23', 450, 450, 0), 
(3, 52, 7, '2014-05-05 09:17:34', 360, 540, 0); 
+0

вы должны поместить http://sqlfiddle.com/ ссылку на такие вопросы, чтобы другие могли попробовать. –

+1

что вы пробовали? покажите запрос, который у вас есть, и где вы застряли. –

+0

Я делал это с php. но хотел сделать это с помощью sql. –

ответ

1

Вам нужен другой стол albums, который держит только следующую информацию: идентификатор, artist_id, имя

И тогда вы можете выполните следующий запрос, чтобы получить запрошенную информацию:

SELECT 
x.id, 
x.name, 
x.date_posted, 
x.pic_location, 
x.website, 
x.press_contact, 
x.bio, 
x.country, 
x.artist_percentage, 
SUM(x.sales) AS sales 
FROM (
(
    SELECT 
     a.*, 
     COUNT(*) AS sales 
    FROM 
     purchases AS p 
     LEFT JOIN music AS m ON p.music_id = m.id 
     LEFT JOIN artists AS a ON m.artist_id = a.id 
    GROUP BY a.id 
    ORDER BY COUNT(*) DESC 
) UNION (
    SELECT 
     a.*, 
     COUNT(*) AS sales 
    FROM 
     purchased_albums AS p 
     LEFT JOIN albums AS ab ON p.album_id = ab.id 
     LEFT JOIN artists AS a ON ab.artist_id = a.id 
    GROUP BY m.album_id,a.id 
    ORDER BY COUNT(*) DESC 
) 
) AS x 
GROUP BY x.id 
ORDER BY x.sales DESC 
+0

, другая таблица - это альбомы, как показано в схеме базы данных. когда я запускаю ваш запрос, я получаю: Table 'c0relief_db.album' не существует –

+0

ok отредактировал ваш ответ, чтобы исправить альбомы, но я получаю эту ошибку сейчас. # 1054 - Неизвестный столбец 'm.album_id' в 'group statement' –

+0

m.album_id следует удалить из группы, просто a.id – Tanatos

1

Это сложно, поэтому вот что вы можете попробовать.

select 
a.id , 
a.name, 
tot_music_count_in_album, 
tot_music_count_in_music, 
sum(tot_music_count_in_album+tot_music_count_in_music) as total_count 
from artists a 
inner join 
( 
select 
count(*) as tot_music_count_in_album, 
m.artist_id 
from 
music m INNER join purchased_albums pa on pa.album_id = m.album_id 
group by m.artist_id 
)t1 on t1.artist_id = a.id 
inner join 
( 
    select 
    count(*) as tot_music_count_in_music, 
    p.music_id, 
    m.artist_id 
    from purchases p INNER join music m on m.id = p.music_id 
    group by m.artist_id 
)t2 on t2.artist_id = a.id 
group by a.id 
order by total_count desc limit 1 
; 

tot_music_count_in_album является общее количество музыки связано с альбомом продаются как полный альбом

tot_music_count_in_music является общее количество музыки, продается как индивидуальная музыка покупки

Вы можете вынуть limit 1 если вы хотите, чтобы все художники перечислили в порядке убывания.

+0

спасибо abhik –

Смежные вопросы