Click to See Complete Forum and Search --> : A Join/Union Query


ChromoX
05-02-2008, 02:19 PM
Ok I have two tables their structures are below:
CREATE TABLE IF NOT EXISTS `songs` (
`id` int(11) NOT NULL auto_increment,
`artist` varchar(128) NOT NULL,
`album` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`track` smallint(6) NOT NULL,
`year` smallint(6) NOT NULL,
`length` int(11) NOT NULL,
`plays` int(11) NOT NULL,
`filename` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;


CREATE TABLE IF NOT EXISTS `play_stats` (
`id` int(11) NOT NULL auto_increment,
`userid` int(11) NOT NULL,
`songid` int(11) NOT NULL,
`plays` int(11) NOT NULL,
`time` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;


Ok so when I query the songs table I want to also query the play_stats table and ask if that song has been played by a certain userid and I want to attach the plays field to my first query. Can anyone get me started in a direction?

toenailsin
05-07-2008, 01:46 AM
SELECT
song.*,
stats.plays AS user_playcount
FROM
songs AS song
LEFT JOIN play_stats AS stats ON ( stats.songid = song.id )
WHERE
song.id = 5
AND stats.userid = 8

Edit: i noticed theres a column for 'plays' in both tables. made it select the user play count as a different name.

ChromoX
05-09-2008, 07:19 AM
Ok... Thanks. I was wondering if anyone could explain this query to me, because I have to make more that do about the same action and I would like to be able to generate them myself.