简体   繁体   English

MySQL选择if else并按语句排序

[英]Mysql select with if else and order by statement

Without any training (and deaf) I developed a town portal system but I gave up on a specific select statement. 我没有经过任何培训(并且充耳不闻),但是开发了城镇门户系统,但是放弃了特定的选择声明。

SELECT `id` FROM `test` ORDER BY FIND_IN_SET(`townid`,'townA'), date DESC LIMIT 3 ;

CREATE TABLE `test` (
  `id` int(5) NOT NULL AUTO_INCREMENT,
  `townid` varchar(10) NOT NULL,
  `data` text NOT NULL,
  `date` date NOT NULL DEFAULT '2017-08-30'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `test` (`id`, `townid`, `data`, `date`) VALUES
(1, 'townB', 'Data for Town B', '2017-08-29'),
(2, 'townA', 'Data for Town A', '2017-08-28'),
(3, 'townA', 'Data for Town A', '2017-08-27'),
(4, 'townA', 'Data for Town A', '2017-08-26'),
(5, 'townC', 'Data for Town C', '2017-08-25'),
(6, 'townB', 'Data for Town B', '2017-08-24');

ALTER TABLE `test`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `test`
  MODIFY `id` int(5) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;COMMIT;

The goal is that 目标是

  • townA select ID 2, 3 and 4 townA选择ID 2、3和4
  • townB select ID 1, 6 and 2 townB选择ID 1、6和2
  • townC select ID 5, 1 and 2 townC选择ID 5、1和2

In other words the town select his OWN articles first in date order with limit 3, ELSE select the limit 3 or remaining of the limit 3 in date order from any other town. 换句话说,该镇从日期顺序中以限制3首先选择其OWN文章,ELSE从任何其他镇中选择限制3或以日期顺序其余3的其余部分。

Neither select WHERE townid = 'townB' or WHERE townid IN ('townB') can deal with the 3 limit problem where I need THREE results even if there is only 1 of 2 entries for Town B 选择“ WHERE townid ='townB'”或“ WHERE townid IN('townB')”都无法处理3个极限问题,我需要三个结果,即使B镇只有2个条目中的1个

You were almost perfect in your sample provided and your query. 您提供的样本和查询几乎完美。 The only thing you need to change is the order by find-in-set clause to DESCENDING. 您唯一需要更改的是DESCENDING的按查找顺序设置子句的顺序。

ORDER BY FIND_IN_SET(townid,'townA') DESC, date DESC

The find_in_set() will return a 1 or 0 based on the thing being found (1) or not (0). find_in_set()将根据被发现(1)或未发现(0)的结果返回1或0。 So you are ordering by those NOT found first, THEN found. 因此,您正在按未找到的那些先订购,然后找到了。 You want the reverse. 您想要相反。 So, even if you have 99 items, and evenly split over each town A, B and C over a span of several days, having the "DESC"ending order on the FIND_IN_SET will say give me all of 'townA' records first, then anyone else after that. 因此,即使您有99件商品,并在几天之内平均分配到每个镇A,B和C,在FIND_IN_SET上使用“ DESC”结束顺序也会说先给我所有“ townA”记录,然后之后的其他人。 THEN, within each set of FOUND (or NOT) records, sort them in descending date order. 然后,在每组FOUND(或NOT)记录中,以降序排列。

Your query is actually just the one "DESC" clause away. 您的查询实际上只是一个“ DESC”子句。

SELECT * 
  FROM test 
 ORDER 
    BY townid = 'townc' DESC -- or 'towna' or 'townb'
     , date DESC
 LIMIT 3;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM