Ok. I've modified the query a bit. It is working fine for small amounts of data but over thousands of rows it is still very very slow. I'm getting a bit confused about the keys and indexes..... So I'll just list everything...
bookmark
contains a list of unique bookmarks. bookmark_id is unique and auto increments.
url is also unique.
bookmark user
a bookmark can have many users (that save it). bookmark_user maps users to bookmarks. A combination of bookmark_id and user_id are unique. bookmark_user also holds some details about a bookmark that are specific to that user (when they bookmarked it, notes and a custom title).
The SQL:
SELECT COUNT(*) AS user_count, b.bookmark_id, b.title, b.url, b.created
FROM bookmark_user bu
INNER JOIN bookmark b ON b.bookmark_id = bu.bookmark_id
WHERE bu.private = 0
GROUP BY b.bookmark_id
ORDER BY user_count DESC;
The Tables:
CREATE TABLE `bookmark` (
`bookmark_id` INT(11) NOT NULL AUTO_INCREMENT,
`title` VARCHAR(255) NOT NULL,
`url` VARCHAR(255) NOT NULL,
`created` DATETIME NOT NULL,
`like` INT(11) NOT NULL,
`dislike` INT(11) NOT NULL,
PRIMARY KEY (`bookmark_id`),
UNIQUE KEY `url` (`url`)
) ENGINE=MYISAM AUTO_INCREMENT=456361 DEFAULT CHARSET=latin1
CREATE TABLE `bookmark_user` (
`bookmark_id` INT(11) NOT NULL,
`user_id` INT(11) NOT NULL,
`title` VARCHAR(255) NOT NULL,
`private` TINYINT(1) NOT NULL,
`notes` TEXT NOT NULL,
`created` DATETIME NOT NULL,
PRIMARY KEY (`bookmark_id`,`user_id`)
) ENGINE=MYISAM DEFAULT CHARSET=latin1
I have tried adding a FK to bookmark user.
ALTER TABLE bookmark_user
ADD FOREIGN KEY (bookmark_id) REFERENCES bookmark(bookmark_id);
Then I get: 456361 row(s) affected
... but there doesn't seem to be any change to the strucure???