Skip to content

Instantly share code, notes, and snippets.

@samholmes
Created February 20, 2011 03:31
Show Gist options
  • Save samholmes/835660 to your computer and use it in GitHub Desktop.
Save samholmes/835660 to your computer and use it in GitHub Desktop.
# Run each statement separately, not all at once
CREATE TABLE `posts` (
`post_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(10) unsigned NOT NULL DEFAULT '0',
`date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`active` tinyint(2) NOT NULL DEFAULT '0',
PRIMARY KEY (`post_id`)
) ENGINE=InnoDB AUTO_INCREMENT=190 DEFAULT CHARSET=utf8;
CREATE TABLE `post_bids` (
`bid_id` bigint(20) NOT NULL AUTO_INCREMENT,
`post_id` bigint(20) unsigned NOT NULL,
`amount` int(11) unsigned NOT NULL,
`date` datetime DEFAULT NULL,
PRIMARY KEY (`bid_id`),
KEY `post_id` (`post_id`),
CONSTRAINT `post_bids_ibfk_1` FOREIGN KEY (`post_id`) REFERENCES `posts` (`post_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1;
INSERT INTO posts
(post_id, user_id, date)
VALUES
(1, 23, NOW());
INSERT INTO post_bids
(post_id, amount, date)
VALUES
(1, 0, NOW()),
(1, 1, NOW()+ INTERVAL 1 DAY),
(1, 2, NOW()+ INTERVAL 2 DAY),
(1, 3, NOW()+ INTERVAL 3 DAY),
(1, 5, NOW()+ INTERVAL 4 DAY),
(1, 123, NOW()+ INTERVAL 5 DAY);
SELECT user_id, amount FROM post_bids
JOIN posts ON posts.post_id = post_bids.post_id
GROUP BY user_id
ORDER BY post_bids.`date` DESC
LIMIT 3;
Getting:
----------------
user_id | amount
----------------
23 | 0
Expecting:
-----------------
user_id | amount
-----------------
23 | 123
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment