数据库
首页 > 数据库> > sql-Zend_Db按字段值排序

sql-Zend_Db按字段值排序

作者:互联网

我正在使用以下命令从模型中输出选择菜单的内容:

$select = $this->select();
$select->order('name');
return $this->fetchAll($select);

但是,我要执行的操作是按特定值排序,然后按名称列排序. SQL看起来像这样:

SELECT * FROM `names` ORDER BY `name` = 'SomeValue' DESC,`name`

示例SQL代码:

CREATE TABLE IF NOT EXISTS `names` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(100) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;

INSERT INTO `names` (`id`, `name`) VALUES
(1, 'rob'),
(2, 'dave'),
(3, 'andy'),
(4, 'paul'),
(5, 'jason'),
(6, 'john');

SELECT *
FROM `names`
ORDER BY `name` = 'john' DESC , `name`

返回值:

6   john
3   andy
2   dave
5   jason
4   paul
1   rob

解决方法:

我相信这是您要寻找的:

$name = 'John';
$order = new Zend_Db_Expr($this->getAdapter()->quoteInto("name = ?", $name) ." DESC, `name`");
$select = $this->select();
$select->order($order);
return $this->fetchAll($select);

标签:zend-db,zend-db-select,sql,mysql,zend-framework
来源: https://codeday.me/bug/20191013/1905286.html