I have 3 tables – user, service and ratings. The user’s primary key is user_id and is a foreign key in the service table. Its also a foreign key in ratings table linked to rated_id (the user id of the person being rated) and rater_id (the user id of the person providing the rating)
Each user has one service and can have mutltiple ratings. If the pushed field in the ratings table is 1, then its a valid rating and can be used. If its 0, its not valid yet and is waiting to be pushed.
I need a query to show me a list of all services, sorted in decending ordered by the users with most ratings. Services belonging to Users with ratings but are not pushed are at the bottom along with services belonging to users with no ratings.
Here is the sql to create the table and data:
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `ratings`
--
-- --------------------------------------------------------
--
-- Table structure for table `ratings`
--
CREATE TABLE IF NOT EXISTS `ratings` (
`unique_id` int(11) NOT NULL AUTO_INCREMENT,
`rater_id` int(11) NOT NULL,
`rated_id` int(11) NOT NULL,
`pushed` int(11) NOT NULL,
PRIMARY KEY (`unique_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
--
-- Dumping data for table `ratings`
--
INSERT INTO `ratings` (`unique_id`, `rater_id`, `rated_id`, `pushed`) VALUES
(1, 4, 1, 1),
(2, 4, 1, 1),
(3, 4, 2, 1),
(4, 4, 3, 0);
-- --------------------------------------------------------
--
-- Table structure for table `service`
--
CREATE TABLE IF NOT EXISTS `service` (
`unique_id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`description` varchar(100) NOT NULL,
PRIMARY KEY (`unique_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
--
-- Dumping data for table `service`
--
INSERT INTO `service` (`unique_id`, `user_id`, `description`) VALUES
(1, 1, 'marks service'),
(2, 2, 'shanes service'),
(3, 3, 'peters service');
-- --------------------------------------------------------
--
-- Table structure for table `user`
--
CREATE TABLE IF NOT EXISTS `user` (
`user_id` int(11) NOT NULL,
`name` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `user`
--
INSERT INTO `user` (`user_id`, `name`) VALUES
(1, 'mark'),
(2, 'shane'),
(3, 'peter'),
(4, 'jobposter');
and here is a query i came up with
SELECT s.*, count(r.rated_id), r.pushed FROM service s
join user u on (u.user_id = s.user_id)
join ratings r on (r.rated_id = u.user_id)
group by r.rated_id
order by r.rated_id
the problem is its incomplete. users with no ratings wont show and if a user has multiple ratings but none are pushed, they will appear high up…
Try this query –