MySQL Count Query excluding records when joining
I have two MySQL tables: One for items and another to log purchases. I'm trying to simply list every product in the items table along with the number of times a specific user has purchased that item. If they have purchased it 0 times I would like for it to still list the item, but say 0. My current query seems exclude records with 0 purchases.
Here's my current query.. I've tried GROUP BY i.item_id as well:
SELECT i.item_id, i.item_name, i.item_sku, i.item_price, COUNT(p.item_id) as purchase_count
FROM items i
LEFT OUTER JOIN purchases p
ON p.item_id = i.item_id
WHERE p.user_id = '1'
GROUP BY p.item_id
ORDER BY i.item_name ASC
Here's the table creation SQL:
CREATE TABLE `items` (
`item_id` int(11) NOT NULL AUTO_INCREMENT,
`item_name` varchar(100) NOT NULL,
`item_sku` varchar(100) NOT NULL,
`item_price` decimal(19,4) NOT NULL,
PRIMARY KEY (`item_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
INSE开发者_JAVA百科RT INTO `items` VALUES(1, 'Item One', 'ITEM1', 99.9900);
INSERT INTO `items` VALUES(2, 'Item Two', 'ITEM2', 19.9900);
INSERT INTO `items` VALUES(3, 'Item Three', 'ITEM3', 10.9900);
INSERT INTO `items` VALUES(4, 'Item Four', 'ITEM4', 4.9900);
CREATE TABLE `purchases` (
`purchase_id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`item_id` int(11) NOT NULL,
`purchase_date` datetime NOT NULL,
PRIMARY KEY (`purchase_id`),
KEY `user_id` (`user_id`,`item_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
INSERT INTO `purchases` VALUES(1, 1, 1, '2011-02-01 12:01:38');
INSERT INTO `purchases` VALUES(2, 1, 2, '2011-01-03 12:01:45');
INSERT INTO `purchases` VALUES(3, 1, 1, '2011-02-08 12:02:17');
Thanks for any help! I thought that as a left outer join it would display all items.
You will likely need a subquery for this, as with your current query the WHERE clause will constrain your results to rows from the purchase table where the user_id = 1. If you remove the WHERE clause from your query you'll see what I mean.
I will update this momentarily with code to support a solution that uses a subquery.
UPDATE Here is the SQL code you will need for your query:
SELECT i.item_id, i.item_name, i.item_sku, i.item_price,
(SELECT COUNT(*) FROM purchases where item_id=i.item_id and user_id='1') as purchase_count
FROM items i
ORDER BY i.item_name ASC
UPDATE
SELECT item_id,
item_name,
item_sku,
item_price,
IF(user_id != 1, 0, purchase_count) AS purchase_count
FROM (SELECT i.*,
p.user_id,
COUNT(p.item_id) AS purchase_count
FROM items i
LEFT JOIN purchases p
ON p.item_id = i.item_id
GROUP BY i.item_id
ORDER BY i.item_name ASC) AS tbl
精彩评论