首頁 >後端開發 >php教程 >mysql如何按特定id排序

mysql如何按特定id排序

WBOY
WBOY原創
2016-06-23 14:05:44947瀏覽

mysql如何按特定id排序


SET FOREIGN_KEY_CHECKS=0;-- ------------------------------ Table structure for `p`-- ----------------------------DROP TABLE IF EXISTS `p`;CREATE TABLE `p` (  `id` int(11) NOT NULL auto_increment,  `name` varchar(255) default NULL,  `categories_id` int(11) default NULL,  PRIMARY KEY  (`id`)) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;-- ------------------------------ Records of p-- ----------------------------INSERT INTO `p` VALUES ('1', 'jimmy', '2');INSERT INTO `p` VALUES ('2', 'tina', '2');INSERT INTO `p` VALUES ('3', 'dd', '2');INSERT INTO `p` VALUES ('4', 'hello', '2');INSERT INTO `p` VALUES ('5', 'world', '2');INSERT INTO `p` VALUES ('6', 'slucky', '2');SET FOREIGN_KEY_CHECKS=0;-- ------------------------------ Table structure for `p_sort`-- ----------------------------DROP TABLE IF EXISTS `p_sort`;CREATE TABLE `p_sort` (  `categories_id` int(10) NOT NULL default '0',  `best_sort_person_id` varchar(100) default NULL,  PRIMARY KEY  (`categories_id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8;-- ------------------------------ Records of p_sort-- ----------------------------INSERT INTO `p_sort` VALUES ('2', '2,5,1');


回复讨论(解决方案)

select * from p, p_sort  order by find_in_set(p.id, p_sort.best_sort_person_id)>0 desc, find_in_set(p.id, p_sort.best_sort_person_id) asc, id 

find_in_set(p.id, p_sort.best_sort_person_id)>0 desc 用于将id=2,5,1的排在前面
find_in_set(p.id, p_sort.best_sort_person_id) asc 用于将id=2,5,1的按出现次序排列

谢谢xuzuning老师,狂亲

SELECT p.*  FROM p INNER JOIN p_sort s ON p.categories_id=s.categories_id    ORDER BY IF(FIND_IN_SET(id,s.best_sort_person_id)>0,FIND_IN_SET(id,s.best_sort_person_id),id) ASC ;

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn