如何从联接表中获取数据

时间:2009-12-01 19:45:22

标签: mysql join

我有两个表连接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

提前致谢。

3 个答案:

答案 0 :(得分:0)

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

c.name as categories_name 

答案 1 :(得分:0)

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']

答案 2 :(得分:-1)

因为在您的查询中,您将“类别”重命名为“c”

尝试更改:

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

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

你也不应该使用*(正如我在编辑之前由其他人指出的那样) - 这应该使错误发生的位置更加明显。