I have three tables:
"products" - contains products
"location" - store location
"product_orders" - joins data from products and location
SQL DUMP:
--
-- Table structure for table `location`
--
CREATE TABLE IF NOT EXISTS `location` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=77 ;
--
-- Dumping data for table `location`
--
INSERT INTO `location` (`id`, `name`) VALUES
(1, 'Miami'),
(2, 'Denver');
-- --------------------------------------------------------
--
-- Table structure for table `products`
--
CREATE TABLE IF NOT EXISTS `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`type` varchar(255) NOT NULL DEFAULT '',
`product` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=6014552 ;
--
-- Dumping data for table `products`
--
INSERT INTO `products` (`id`, `type`, `product`) VALUES
(1, 'shirt', 'red shirt'),
(2, 'shirt', 'red shirt'),
(3, 'pants', 'blue pants'),
(4, 'pants', 'blue pants');
-- --------------------------------------------------------
--
-- Table structure for table `product_orders`
--
CREATE TABLE IF NOT EXISTS `product_orders` (
`product_id` int(11) NOT NULL,
`location_id` int(11) NOT NULL,
`status` varchar(255) NOT NULL,
PRIMARY KEY (`product_id`,`location_id`),
KEY `ix_product_orders` (`location_id`),
KEY `ix_product_orders_1` (`product_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `product_orders`
--
INSERT INTO `product_orders` (`product_id`, `location_id`, `status`) VALUES
(1, 1, 'sold'),
(2, 2, 'sold'),
(1, 2, 'available'),
(2, 1, 'sold');
If I want to select all sold products from store 'miami - this query works:
SELECT * FROM `products`
INNER JOIN `product_orders`
ON `product_orders`.`product_id`= `products`.`id`
WHERE `product_orders`.`location_id` = '1'
AND
status = 'sold'
How would you rewrite to delete all sold products from the miami store? My query is not working:
DELETE `products` FROM `products`
INNER JOIN `product_orders`
ON `product_orders`.`location_id` = `products`.`id`
WHERE `product_orders`.`location_id` = '2'
AND
status = 'sold'
DELETE FROM products WHERE id IN (SELECT location_id FROM products_orders WHERE location = 'miami' AND status = 'sold');
Try this one,
DELETE `products` FROM `products` INNER JOIN `products_orders`
ON `products_orders`.`location_id` = `products`.`id`
WHERE `products_orders`.`location` = 'miami'
AND
status = 'sold'
OR
DELETE prod FROM `products` AS prod INNER JOIN `products_orders`
ON `products_orders`.`location_id` = `products`.`id`
WHERE `products_orders`.`location` = 'miami'
AND
status = 'sold'
I am not sure how you have set foreign keys in your tables. But looking at it with the most primary assumptions, product table holds products data and location holds location data. In your common table product orders you are having one foreign key to products table by product id and one another relation to location table by location.
So to back my comment, I am posting the following query. It is your query with a change to a field that I ASSUME WAS A TYPO....in your query. :-) Again as foampile said, I might be doing it with consistency...
DELETE FROM `products`
INNER JOIN `products_orders`
ON `products_orders`.`product_id` = `products`.`id`
WHERE `products_orders`.`location` = 'miami'
AND `products_orders`.status = 'sold'
;
Related
I have a MYSQL table called tbl_product
Another table called tb_opciones_productos
And a third table called tb_opciones
I need to show every item from tbl_product as follows:
How can I get one item from tbl_product and the needed rows from tb_opciones_producto to get the needed result?
EDIT:
This is my current query proposal:
SELECT tbl_product.*,
GROUP_CONCAT( (SELECT CONCAT(tb_opciones.nombre, "(+$", tb_opciones.precio, ")")
FROM tb_opciones WHERE tb_opciones.id_opcion = tb_opciones_productos.id_opcion) SEPARATOR "<br>" ) as options FROM tbl_product
INNER JOIN tb_opciones_productos ON tbl_product.id = tb_opciones_productos.producto
I've create a little sqlfiddle to test : http://sqlfiddle.com/#!9/fc3316/16
You can GROUP_CONCAT a sub-query. It may not be optimized, but it do the job.
PS: next time, can you provide a sample structure ?
Structure :
CREATE TABLE IF NOT EXISTS `products` (
`id` int(6) unsigned NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
INSERT INTO `products` (`id`, `name`) VALUES
(1, 'Product Lorem'),
(2, 'Product Ipsum');
CREATE TABLE IF NOT EXISTS `products_options` (
`id_product` int(6) unsigned NOT NULL,
`id_option` int(6) unsigned NOT NULL,
PRIMARY KEY (`id_product`, `id_option`)
) DEFAULT CHARSET=utf8;
INSERT INTO `products_options` (`id_product`, `id_option`) VALUES
(1, 1),
(1, 2),
(1, 3),
(2, 3);
CREATE TABLE IF NOT EXISTS `options` (
`id` int(6) unsigned NOT NULL,
`name` varchar(255) NOT NULL,
`value` double NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
INSERT INTO `options` (`id`, `name`, `value`) VALUES
(1, 'Option A', 42),
(2, 'Option B', 6),
(3, 'Option C', 12);
Request :
SELECT products.*,
GROUP_CONCAT(options.name, " (+$", options.value, ")" SEPARATOR "<br>")
FROM products
INNER JOIN products_options
ON products.id = products_options.id_product
INNER JOIN options
ON products_options.id_option = options.id
GROUP BY products.id
With your Structure, I think this one will work :
SELECT tbl_product.*,
GROUP_CONCAT(tb_opciones.nombre, " (+$", tb_opciones.precio, ")" SEPARATOR "<br>")
FROM tbl_product
INNER JOIN tb_opciones_productos
ON tbl_product.id = tb_opciones_productos.producto
INNER JOIN tb_opciones
ON tb_opciones_productos.opcion = tb_opciones.id
GROUP BY tbl_product.id
Hi I want a SQL statement that would return all courses
having at least 2 students enrolled which is ordered by course with the
greatest number of students. I am pretty new with SQL stuff and I am finding it bit difficult.
here is my current database
CREATE TABLE `course` (
`CourseID` char(11) NOT NULL,
`Course_name` varchar(22) DEFAULT NULL,
`hours_per_week` varchar(22) DEFAULT NULL,
`Start_date` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `course`
--
INSERT INTO `course` (`CourseID`, `Course_name`, `hours_per_week`, `Start_date`) VALUES
('C001', 'Cert 1', '15', '2012-02-01'),
('C002', 'Cert 2', '20', '2012-02-02'),
('C003', 'Cert 3', '16', '2012-02-03'),
('C004', 'Cert 4', '20', '2012-02-13');
-- --------------------------------------------------------
--
-- Table structure for table `enrolment`
--
CREATE TABLE `enrolment` (
`studentID` char(11) NOT NULL,
`courseID` char(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `enrolment`
--
INSERT INTO `enrolment` (`studentID`, `courseID`) VALUES
('S001', 'C001'),
('S002', ' C001'),
('S003', ' C002'),
('S004', ' C002'),
('S005', ' C004');
-- --------------------------------------------------------
--
-- Table structure for table `student`
--
CREATE TABLE `student` (
`StudentID` char(11) NOT NULL,
`FirstName` varchar(22) DEFAULT NULL,
`LastName` varchar(22) DEFAULT NULL,
`DOB` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `student`
--
INSERT INTO `student` (`StudentID`, `FirstName`, `LastName`, `DOB`) VALUES
('S001', 'Alison', 'Tildesley', '1984-05-09'),
('S002', 'Fred', 'Nile', '1940-03-03'),
('S003', 'Christine', 'Anu', '1970-09-01'),
('S004', 'Jame', 'Brown', '1976-02-03'),
('S005', 'Mark', 'Oliphant', '1958-03-10'),
('S006', 'George', 'Bush', '1951-11-28');
This is what I have tried
SELECT FROM COURSES WHERE STUDENT_ID >=2
I know I have to add student_id row into my course table but I am still confused how to get desired results. I am sorry I am very new to database and MYSQL statements.
This should do:
SELECT C.CourseID, C.Course_name, COUNT(E.StudentID) Students_num
FROM course C
JOIN enrolment E USING(CourseID)
GROUP BY C.CourseID, C.Course_name
HAVING Students_num >= 2
ORDER BY Students_num DESC, C.Course_name
This will extract all courses joined with their enrollment records, and then group them by the course ID and name, counting the number of students; the last HAVING clause will discard all records that, after the grouping, will have less than 2 students.
Here is a working SQL fiddle for testing.
Not tested ;)
select
c.courseID, count(0)
from course c, enrolment e
where c.CourseID = e.CourseID
group by
c.courseID
having
count(0) >= 2
order by
count(0) desc
I have three MySQL tables:
For example
A Table is menu ID, name
B table is customer_order ID, order_date
C table is order_item ID, menu_item_id, customer_order_id, order_quantity
I try to output name, sum(order_quantity) in this month
Currently i have two separate query which working ok, but the second query is inside of foreach loop, which seem not so good.
First query which output all the menu items:
$results = $wpdb->get_results( "SELECT * FROM menu WHERE post_id = $pid ORDER BY sort_order ");
Second query will output total of each item sold on each month:
$total = $wpdb->get_col( "SELECT SUM(oi.order_item_quantity)
from order_item as oi
INNER JOIN customer_order as ho ON ho.ID = oi.order_id
WHERE oi.order_item_id = $subC->ID AND YEAR(ho.order_date) = $current_year AND MONTH(ho.order_date) = $current_month ");
I try to merge the two queries into one query, which has taken me whole day but still not able to solve it, can anyone give me some help please.
update
thanks Rene.
Select m.name, m.name as name, sum(oi.order_item_quantity) as sold_monthly from menu as m left join order_item as oi on oi.order_item_id = m.ID left join cusomter_order as co on co.ID = oi.order_id where m.post_id = 110 group by m.ID, m.name
this will output
name sold_monthly
Sushi Lunch Special NULL
Sushi Lunch 19
Sashimi Lunch 61
jason NULL
egg roll NULL
if i add YEAR(co.order_date) = 2016 AND MONTH(co.order_date) = 9
which i only get
name sold_monthly
Sushi Lunch 7
Sashimi Lunch 14
how can i keep sushi lunch special, jason, egg roll, the null item, when i add the YEAR(co.order_date) = 2016 AND MONTH(co.order_date) = 9.
here i try
(year(co.order_date) = 2016 and month(co.order_date) = 10) or sold_monthly is null
which give me a query error
update
thanks Rene again
it's working now
(year(co.order_date) = 2016 and month(co.order_date) = 10) or co.order_date is null
finally solve it, upper have little bug, when i change business_id which may not catch the result i want, so i am add a subquery to it.
Select m.*, p.sold_monthly from menu as m left join ( SELECT SUM(oi.order_item_quantity) as sold_monthly, oi.order_item_id as ID, oi.order_item_name from order_item as oi LEFT JOIN cusomter_order as ho ON ho.ID = oi.order_id WHERE ho.business_id = $pid AND (year(ho.order_date) = $current_year and month(ho.order_date) = $current_month) OR ho.order_date is NULL GROUP by oi.order_item_id )p on p.ID = m.ID where m.post_id = $pid
So you're trying to get a list per post_id limited by the selected month.
The following query will yield that for the following sample data.
SELECT m.ID as ID, m.Name as Name, SUM(oi.order_quantity) as Quantity
FROM menu as m
LEFT JOIN order_item as oi ON oi.menu_item_id = m.ID
LEFT JOIN customer_order as co ON co.ID = oi.customer_order_id
WHERE m.post_id = 0 AND YEAR(co.order_date) = 2016 AND MONTH(co.order_date) = 9 OR co.order_date is NULL
GROUP BY m.ID,m.Name,m.sort_order
ORDER BY m.sort_order
Sample Data
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
DROP TABLE IF EXISTS `customer_order`;
CREATE TABLE `customer_order` (
`ID` int(11) NOT NULL,
`order_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_german2_ci;
TRUNCATE TABLE `customer_order`;
INSERT INTO `customer_order` (`ID`, `order_date`) VALUES
(1, '2016-09-06 00:00:00'),
(2, '2016-09-13 00:00:00'),
(3, '2016-08-09 00:00:00'),
(4, '2016-09-19 00:00:00');
DROP TABLE IF EXISTS `menu`;
CREATE TABLE `menu` (
`ID` int(11) NOT NULL,
`sort_order` int(11) NOT NULL,
`post_id` int(11) NOT NULL,
`Name` varchar(20) COLLATE utf8_german2_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_german2_ci;
TRUNCATE TABLE `menu`;
INSERT INTO `menu` (`ID`, `sort_order`, `post_id`, `Name`) VALUES
(2, 0, 0, 'Test 1'),
(4, 1, 0, 'Test 2'),
(5, 2, 0, 'Test 3');
DROP TABLE IF EXISTS `order_item`;
CREATE TABLE `order_item` (
`ID` int(11) NOT NULL,
`menu_item_id` int(11) NOT NULL,
`customer_order_id` int(11) NOT NULL,
`order_quantity` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_german2_ci;
TRUNCATE TABLE `order_item`;
INSERT INTO `order_item` (`ID`, `menu_item_id`, `customer_order_id`, `order_quantity`) VALUES
(1, 2, 1, 1),
(2, 2, 2, 3),
(3, 4, 1, 1),
(4, 4, 2, 4),
(5, 2, 3, 3),
(6, 4, 3, 1),
(7, 2, 4, 4);
ALTER TABLE `customer_order`
ADD PRIMARY KEY (`ID`);
ALTER TABLE `menu`
ADD PRIMARY KEY (`ID`),
ADD KEY `idx_pid` (`post_id`);
ALTER TABLE `order_item`
ADD PRIMARY KEY (`ID`),
ADD KEY `idx_coid` (`customer_order_id`),
ADD KEY `idx_miid` (`menu_item_id`);
ALTER TABLE `customer_order`
MODIFY `ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
ALTER TABLE `menu`
MODIFY `ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
ALTER TABLE `order_item`
MODIFY `ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
ALTER TABLE `order_item`
ADD CONSTRAINT `CostomerOrderConstrain` FOREIGN KEY (`customer_order_id`) REFERENCES `customer_order` (`ID`),
ADD CONSTRAINT `MenuItemConstrain` FOREIGN KEY (`menu_item_id`) REFERENCES `menu` (`ID`);
Good luck integrating the query, let me know if it worked.
Update: Updated sample data to reproduce the actual problem. Updated the Solution Query.
I have two tables: categories and items. i have stored categories using nested set structure. Categories have items. Items can be only added to leaf nodes of a root category.
For eg:
Categories
Vehicles
Bikes
Bajaj
Automobiles
Art & Antiques
Amateur Art
Items can be added to category Bajaj, Automobiles and Amateur Art in this case.
Lets say there are 2 items inside Bajaj, 5 items inside Automobiles, 2 inside Amateur Art
For root level categories I want to display as follow:
- Vehicles (7 items)
- Art & Antiques (2 items)
How can I do this ?
Here is the sql dump to work with some sample data
--
-- Table structure for table `categories`
--
CREATE TABLE IF NOT EXISTS `categories` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`parent_id` int(11) DEFAULT NULL,
`title` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
`lft` int(11) NOT NULL,
`lvl` int(11) NOT NULL,
`rgt` int(11) NOT NULL,
`root` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `IDX_3AF34668727ACA70` (`parent_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=28 ;
--
-- Dumping data for table `categories`
--
INSERT INTO `categories` (`id`, `parent_id`, `title`, `lft`, `lvl`, `rgt`, `root`) VALUES
(22, NULL, 'Vehicles', 1, 0, 8, 22),
(23, 22, 'Bikes', 2, 1, 5, 22),
(24, 23, 'Bajaj', 3, 2, 4, 22),
(25, 22, 'Automobiles', 6, 1, 7, 22),
(26, NULL, 'Art & Antiques', 1, 0, 4, 26),
(27, 26, 'Amateur Art', 2, 1, 3, 26);
-- --------------------------------------------------------
--
-- Table structure for table `items`
--
CREATE TABLE IF NOT EXISTS `items` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`category_id` int(11) NOT NULL,
`title` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_403EA91BA33E2D84` (`category_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
--
-- Dumping data for table `items`
--
INSERT INTO `items` (`id`, `category_id`, `title`) VALUES
(1, 24, 'Pulsor 150 cc'),
(2, 24, 'Discover 125 cc'),
(3, 27, 'Art of dream'),
(4, 25, 'Toyota Car');
--
-- Constraints for dumped tables
--
--
-- Constraints for table `categories`
--
ALTER TABLE `categories`
ADD CONSTRAINT `FK_3AF34668727ACA70` FOREIGN KEY (`parent_id`) REFERENCES `categories` (`id`) ON DELETE SET NULL;
--
-- Constraints for table `items`
--
ALTER TABLE `items`
ADD CONSTRAINT `FK_403EA91BA33E2D84` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`) ON DELETE CASCADE;
root nodes have NULL in the field of parent_id
Update:
I was able to fetch for roots using this query:
SELECT c.id,c.title,cte.co FROM categories c
JOIN
(SELECT
c0_.id,c0_.root,COUNT(i.id) co
FROM
categories c0_
JOIN items i ON c0_.id=i.category_id
WHERE c0_.rgt = 1 + c0_.lft
GROUP BY c0_.id
) cte
ON cte.root=c.id
WHERE c.parent_id is null
The above query works for root level category. Now when the user clicks on root level category, I want to do the same.
for eg when somebody clicks on vehicles I should get:
Bikes (2)
Automobiles (5)
For that I tried :
SELECT c.id,c.title,cte.co FROM categories c
JOIN
(SELECT
c0_.id,c0_.root,COUNT(i.id) co
FROM
categories c0_
JOIN items i ON c0_.id=i.category_id
WHERE
c0_.rgt = 1 + c0_.lft
GROUP BY c0_.id
) cte
ON cte.root=c.id
WHERE c.parent_id=1
This returned empty result set. what is wrong in this query ?
SELECT parent.title,
( SELECT count(i.id) count FROM items i
WHERE category_id IN
(
SELECT child.id FROM categories child WHERE child.lft>=parent.lft AND
child.rgt<=parent.rgt AND child.root=parent.root
)
)
FROM categories parent
WHERE parent.parent_id=#parent_id;
Please inform me if this does not work
How about something like this:
SELECT COUNT(items.id),
(SELECT lookup.title
FROM categories lookup
WHERE lookup.id = categories.root)
FROM items, categories
WHERE categories.id = items.category_id
GROUP BY categories.root;
based on the input from the script above gives me:
3 | Vehicles
1 | Art & Antiques
to select for a particular root add
AND categories.root = #id
where #id is your root id you're looking for.
Alternatively if you want to select by the root name do something (scary) like this:
SELECT title, total
FROM
(SELECT COUNT(items.id) total,
(SELECT lookup.title
FROM categories lookup
WHERE lookup.id = categories.root) title
FROM items, categories
WHERE categories.id = items.category_id
GROUP BY categories.root;
) AS some_table
WHERE some_table.title = #root_name
where #root_name is the name of your root node (in quotes of course)
Something like this should work.
select c1.title, count(*) itemcount
from categories c1 join categories c2
on c2.parent_id = c1.id
join items on items.category_id = c2.id
group by c1.title
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 -
SELECT
s.*, r.rated_id, r.pushed_count
FROM
service s
JOIN user u ON
u.user_id = s.user_id
LEFT JOIN (
SELECT
rated_id, COUNT(IF(pushed = 1, 1, NULL)) pushed_count
FROM
ratings
GROUP BY
rated_id
) r
ON r.rated_id = u.user_id
ORDER BY
r.pushed_count DESC
You might try this:
SELECT u.name,
s.DESCRIPTION,
COUNT(r.rated_id) rated,
r.pushed
FROM USER u
LEFT JOIN SERVICE s
ON ( u.user_id = s.user_id )
LEFT JOIN ratings r
ON ( r.rated_id = u.user_id )
GROUP BY u.name,
r.rated_id,
r.pushed
ORDER BY r.pushed DESC,
3 DESC,
u.name
I am not hundred percent sure about left joining user with services. Remove left if you require users to have services in order to participate in ratings.