如何在codeigniter中编写这个复杂的查询

时间:2018-04-17 07:29:09

标签: codeigniter query-builder

SELECT 
    fname,
    lname,
    email,
    phone,
    activities.activitydescription, 
    package.PackageName, 
    reservationyurt.arrvdate 
FROM 
    client
    INNER JOIN activities ON client.activityid = activities.activityid)
    INNER JOIN package ON client.packageid = package.packageid)
    INNER JOIN reservationyurt ON client.packageid = reservationyurt.packageid)
WHERE 
    email = 'tr@gmail.com' 
    AND clientid IN (
        SELECT MAX(clientid)
        FROM client GROUP BY email
    )

我想使用CodeIgniter QueryBuilder编写此查询。这就是我到目前为止所得到的......

$email = array('email' => $this->input->post('email'));
$this->db->select('fname, lname, email, phone, activities.activitydescription, package.pkgname, reservationyurt.arrvdate');
$this->db->from('client');
$this->db->join('activities', 'client.activityid = activities.activityid');
$this->db->join('package', 'client.packageid = package.packageid');
$this->db->join('reservationyurt', 'client.packageid = reservationyurt.packageid');
$this->db->where('email',$email);
$this->db->where('clientid');

2 个答案:

答案 0 :(得分:1)

希望这对您有用:

使用where_in作为最后一部分

$this->db->select('fname, lname, email, phone, activities.activitydescription, package.pkgname, reservationyurt.arrvdate');
$this->db->from('client');
$this->db->join('activities', 'activities.activityid = client.activityid');
$this->db->join('package', 'package.packageid = client.packageid');
$this->db->join('reservationyurt', 'reservationyurt.packageid = client.packageid');
$this->db->where('client.email',$email);
$this->db->where_in('client.clientid',"SELECT MAX(clientid) FROM client GROUP BY email)");

更多信息:https://www.codeigniter.com/user_guide/database/query_builder.html#looking-for-specific-data

答案 1 :(得分:0)

查询生成器是一个很好的工具,但您并不总是需要使用它。除非您的查询有条件地需要更改selectwhere或查询的其他部分,否则使用query()

通常会更容易
$sql = "SELECT 
    fname,
    lname,
    email,
    phone,
    activities.activitydescription, 
    package.PackageName, 
    reservationyurt.arrvdate 
FROM client
    INNER JOIN activities ON client.activityid = activities.activityid)
    INNER JOIN package ON client.packageid = package.packageid)
    INNER JOIN reservationyurt ON client.packageid = reservationyurt.packageid)
WHERE email = ? AND 
    clientid IN (SELECT MAX(clientid) FROM client GROUP BY email)";

$data = array('tr@gmail.com');
$query = $this->db->query($sql, $data);
$dataset = $query->result();

基本上,正确的查询构建器调用集将创建上面的字符串,但它将执行数百行代码来实现。

请注意WHERE email = ?中使用Query Binding