简体   繁体   English

Mysql在同一个表上连接查询

[英]Mysql join query on same table

I have table like 我有桌子

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`)
)

now here I want records like 现在我在这里想要记录

id,title,parent_title,status ID,标题,PARENT_TITLE,状态

means I want relative title in place of parent_id(at here parent_title) 意味着我想用相对标题代替parent_id(在这里是parent_title)

Here it is mate: 在这里是伙伴:

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 code Cakephp代码

In Category Controller 在类别控制器中

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

In category Model 在类别模型中

var $belongsTo = array(

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

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

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