Answer the question
In order to leave comments, you need to log in
How to sort records in MYSQL by "floating" parameter?
There is a table with a list of news for the auto-site. Some of the news are not attached to anything, some are brand-specific, some are category-specific (tuning, new items, auto shows...).
Task: pull out 3 latest news with one MySQL query - everything is simple, but:
If we are on the page of a certain brand, there should be news about this brand at the top, and if there are less than three of them (not all brands have their own news), then below them general news. Same with the category. On all general pages, news is displayed in reverse sorting by date added.
Base structure:
CREATE TABLE IF NOT EXISTS `news_test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`brand_id` int(11) NOT NULL,
`cat_id` int(11) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `person` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
INSERT INTO `news_test` (`id`, `name`, `brand_id`, `cat_id`, `date`) VALUES
(1, 'Представлен новый Volvo XC90', 5, 2, '2015-11-01 00:00:00'),
(2, 'Тюнинг подвески', 0, 4, '2015-11-03 00:00:00'),
(3, 'Просто новость', 0, 0, '2015-11-06 00:00:00'),
(4, 'KIA Sorento получил 5 звезд EuroNCAP', 12, 0, '2015-11-11 00:00:00');
@brand и @cat
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question