同一个表上的Mysql连接查询


Mysql join query on same table

我有一个表,像

CREATE TABLE IF NOT EXISTS `categories` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `parent_id` int(11) NOT NULL DEFAULT '0',
  `status` enum('1','2') NOT NULL COMMENT '''1''=active,''2''=inactive',
  PRIMARY KEY (`id`)
)

现在我想要像

这样的记录

id、标题、parent_title地位

表示我想用相对标题代替parent_id(这里是parent_title)

是这样的:

SELECT c1.id, c1.title, c2.title as parent_title, c1.status
FROM categories c1
LEFT JOIN categories c2 ON (c2.id = c1.parent_id)
$fields = array('c1.id, c1.title, c2.title as parent_title, c1.status');
        $joins = array();
            $joins[] = array(
                'table' => 'categories',
                'foreignKey' => false,
                'conditions' => 'c2.id = c1.parent_id',
                'type' => 'LEFT',
                'alias' => 'c2',
            );
$this->paginate = compact('fields', 'joins');

Cakephp代码

In Category Controller

$fields=array(
            'Category.*',
            'ParentCategory.title'
            );
$data = $this->Category->find("all",array(
                'fields' => $fields,
                'recursive'=>0
            ));

目录模型

var $belongsTo = array(
        'ParentCategory' => array(
            'className' => 'Category',
            'foreignKey' => 'parent_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
);