MySQL query: pull all the other categories minus the one that has been saved
I really need some help with forming a MySQL query that I just cannot work out. On my website I have a system in place that will hopefully remember some selections that user made when they last visited the site.
On the site the user can select which category they wish to read开发者_运维问答 the content of next time they come to site. That setting will be remembered but the menu should be displayed slightly different. It should show all the other categories minus the one that has been saved.
So if I have these categories,
- Blog
- Inspiration
- Case Studies
and the user saved Blog, the next time they come to the site the categories list should just be
- Inspiration
- Case Studies.
How can this data be pulled from the database?
Currently I have a table that identifies the user via a unique cookie id:
CREATE TABLE IF NOT EXISTS `cookieTable` (
`cookieEntryId` int(11) NOT NULL AUTO_INCREMENT,
`cookieId` varchar(32) NOT NULL,
`expirationDate` int(10) NOT NULL,
PRIMARY KEY (`cookieEntryId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
I have a category table
CREATE TABLE IF NOT EXISTS `categoryTable` (
`categoryId` int(11) NOT NULL AUTO_INCREMENT,
`categoryTitle` varchar(25) NOT NULL,
`categoryAbstract` varchar(150) NOT NULL,
`categorySlug` varchar(25) NOT NULL,
`categoryIsSpecial` int(1) DEFAULT NULL,
`categoryOnline` int(1) DEFAULT NULL,
`dashboardUserId` int(11) NOT NULL,
`categoryDateCreated` int(10) NOT NULL,
PRIMARY KEY (`categoryId`),
KEY `dashboardUserId` (`dashboardUserId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
And I have the table that saves what categories the user has saved,
CREATE TABLE IF NOT EXISTS `userMenuTable` (
`menuEntryId` int(11) NOT NULL AUTO_INCREMENT,
`categoryId` int(11) NOT NULL,
`cookieId` varchar(32) NOT NULL,
PRIMARY KEY (`menuEntryId`),
KEY `categoryId` (`categoryId`,`cookieId`),
KEY `cookieId` (`cookieId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6;
The following query should get the categories the user hasn't saved assuming the cookieId stays constant for a user. If it doesn't you should put a userId into the userMenuTable instead. Just replace USERSCOOKIEID with their actual cookie ID.
SELECT * FROM categoryTable WHERE categoryId not in
(SELECT categoryId FROM userMenuTable WHERE cookieId = 'USERSCOOKIEID') as x
精彩评论