如何从一个连接表数据(How to get data from a joined table)

2019-11-02 09:26发布

我有两个表加入了与c.id = p.category_id。 我想categories.name但它给出了一个错误。 谁能告诉我如何从一个连接表的数据吗?

function getGalleryone(){
     $data = array();
     $query = 'SELECT *
     FROM products AS p
     JOIN categories AS c
     ON c.id = p.category_id
     WHERE c.name = "Galleri1"
     AND p.status = "active"' ;
     $Q = $this->db->query($query);
     /*
     $this->db->select('*');
     $this->db->where('categories.name','Galleri 1');
     $this->db->where('products.status', 'active');
     $this->db->join('categories', 'categories.id = products.category_id');
     $this->db->order_by('name','random'); 
     $Q = $this->db->get('products');
     */
     if ($Q->num_rows() > 0){
       foreach ($Q->result_array() as $row){
         $data = array(
            "id" => $row['id'],
        "name" => $row['name'],
            "shortdesc" => $row['shortdesc'],
        ...
            ...
        "category" => $row['categories.name']
            );
       }
    }
    $Q->free_result();    
    return $data;  

数据库产品

CREATE TABLE IF NOT EXISTS `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `shortdesc` varchar(255) NOT NULL,
  `longdesc` text NOT NULL,
  `thumbnail` varchar(255) NOT NULL,
  `image` varchar(255) NOT NULL,
  `class` varchar(255) DEFAULT NULL,
  `grouping` varchar(16) DEFAULT NULL,
  `status` enum('active','inactive') NOT NULL,
  `category_id` int(11) NOT NULL,
  `featured` enum('true','false') NOT NULL,
  `price` float(4,2) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=20 ;

数据库分类

CREATE TABLE IF NOT EXISTS `categories` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `shortdesc` varchar(255) NOT NULL,
  `longdesc` text NOT NULL,
  `status` enum('active','inactive') NOT NULL,
  `parentid` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ;
...
...

错误信息

A PHP Error was encountered

Severity: Notice

Message: Undefined index: categories.name

Filename: models/mproducts.php

Line Number: 111

提前致谢。

Answer 1:

使用在选择你有2列名为“名” *。 指定*到所需的列,而(这将提高在任何情况下的性能),如

c.name as categories_name 


Answer 2:

categories.name列实际上是要被退回刚刚$row['name']在结果集中,而不是$row['categories.name'] 由于products也有一个name栏,一个是要取代其他。 而不是使用选择各个领域的*通配符,您应该指定哪些字段,你想退回。 例如:

 SELECT p.*, c.name AS category
 FROM products AS p
 JOIN categories AS c
 ON c.id = p.category_id
 WHERE c.name = "Galleri1"
 AND p.status = "active"

然后,你可以参考一下类别名称为$row['category']



Answer 3:

因为在你的查询您重命名“类别”为“C”

尝试改变:

"category" => $row['categories.name']

"category" => $row['c.name']

你不应该使用*或者(由别人指出我编辑在此之前) - 原本应该变得更加明显,其中错误是什么。



文章来源: How to get data from a joined table
标签: mysql join