我有3个表,商店,促销,store_promo_link
我想从商店中选择10行。商店必须每个都有1个特色促销,如果没有特色促销,那么选择最新的促销
CREATE TABLE IF NOT EXISTS `stores` (
`StoreID` int(11) NOT NULL AUTO_INCREMENT,
`StoreBranch` varchar(255) NOT NULL,
`StoreName` varchar(255) NOT NULL,
`IsFeatured` enum('0','1') NOT NULL DEFAULT '0',
`OrderNumber` int(11) NOT NULL,
PRIMARY KEY (`StoreID`),
KEY `StoreBranch` (`StoreBranch`),
FULLTEXT KEY `StoreDesc` (`StoreDesc`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=51 ;
CREATE TABLE IF NOT EXISTS `promos` (
`PromoID` bigint(20) NOT NULL AUTO_INCREMENT,
`Title` varchar(255) NOT NULL,
`Description` text NOT NULL,
`Photo` varchar(255) NOT NULL,
`IsFeatured` enum('0','1') NOT NULL,
`DateAdded` datetime NOT NULL,
`DateUpdated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`PromoID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=36 ;
CREATE TABLE IF NOT EXISTS `store_promo_link` (
`ID` bigint(20) NOT NULL AUTO_INCREMENT,
`StoreID` int(11) NOT NULL,
`PromoID` int(11) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=149 ;
这是我的代码,但它从promos
返回第一行SELECT s.StoreBranch, s.StoreName, s.StoreID , p.* FROM `stores` s
INNER JOIN store_promo_link sp ON s.StoreID = sp.StoreID
INNER JOIN (SELECT * FROM promos ORDER BY IsFeatured DESC, DateAdded DESC) p ON sp.PromoID = p.PromoID
GROUP BY sp.StoreID
ORDER BY OrderNumber = 0, OrderNumber, s.IsFeatured DESC LIMIT 10
修改 我想选择10个独特的商店。每个商店都有多个促销。我只想为每家商店选择1个特色(IsFeature ='1')促销。如果没有精选促销,则必须选择最新的促销。
谢谢!
答案 0 :(得分:0)
您的查询工作正常。如果促销是特色你得到它,如果没有特色促销,你得到最后一个。请参阅我撰写的SQLFiddle。
没有商店重复:
StoreBranch StoreName StoreID PromoID Title Description Photo IsFeatured DateAdded DateUpdated
be ikea 1 2 2por1 promo2 foto2 1 September, 02 2015 00:00:00 September, 07 2015 10:48:54
es mediamarkt 2 4 pollos promo4 foto4 0 September, 04 2015 00:00:00 September, 07 2015 10:48:54