codeigniter连接查询同一个表

时间:2013-10-25 04:39:01

标签: mysql sql join left-join codeigniter-2

我有一个用户订单的表格结构,如下所示。现在我希望查询将在codeigniter中

  1. 选择shop_id列表属于user_id
  2. 选择产品列表,然后属于shop_id和user_id
  3. 然后它会进入一个单一阵列。
  4. 像这样:请给我一个查询。我尝试过单独的功能,但我需要一个单独的功能使用join的 user_id -> shop_id -> products [0] ->product_name1 [1] -> product_name2`

    Table : at_order
    +----+------------+-----------+------------+
    | id | user_id    | shop_id   | product-id |
    +----+------------+-----------+------------+
    |  1 | 3          | 3         |          32|
    |  2 | 3          | 3         |          24|
    |  3 | 3          | 4         |          3 |
    |  4 | 4          | 3         |          8 |
    |  5 | 4          | 5         |          4 |
    |  6 | 4          | 6         |          1 |
    +----+------------+-----------+------------+
    
    function main () 
    {
        SELECT
          `shop_id`
        FROM (`at_order`)
        WHERE `user_id` = '3'
        GROUP BY `shop_id`;
        one($shop_id,$user_id);
    
    }
    
    function one () 
    {
        SELECT
          `product_id`,
          `order_status`
        FROM (`at_order`)
        WHERE `user_id` = '3'
            AND `shop_id` = '5';
        two($shop_id,$product_id);
    }
    
    function two () 
    {
        SELECT *
        FROM (`at_product`)
        WHERE `product_id` = '35'
            AND `shop_id` = '5'
    }
    

    我已经在三个函数中编写了这三个查询,并将这些函数连接到主函数

    Please help
    

1 个答案:

答案 0 :(得分:2)

您可以使用仅需要用户ID的单个查询,并将获取所有必需的内容。

function getUserProducts($user_id){

    $query  =   "SELECT
                    as.shop_name,
                    ap.*
                FROM at_order ao
                LEFT JOIN at_product ap 
                    ON ap.product_id = ao.product_id
                LEFT JOIN at_shops as
                    ON as.shop_id = ao.shop_id
                WHERE ao.user_id = $user_id";
    return $this->db->query($query)->result_array();

    //Or Active Record Version

    return $this->db
                ->select('ao.shop_name')
                ->select('ap.*')
                ->from('at_order ao')
                ->join('at_product ap ','ap.product_id = ao.product_id','left')
                ->join('at_shops as','as.shop_id = ao.shop_id','left')
                ->where('ao.user_id',$user_id)
                ->get()
                ->result_array();
}