Welcome Guest, Not a member yet? Register   Sign In
How do I write this SQL statement ?
#1

[eluser]Unknown[/eluser]
Hi everyone,

I have this SQL statement :

Select * from `abc_table` abc
where abc.field1 = 1 and
(
abc.field2 = 2 and
(abc.field = 3 or abc.field4 = 4)
);

If don't use $this->db->query() statement, how do I write this statement (by $this->db->where...)

Thanks for helping.
#2

[eluser]sybrex[/eluser]
Have a look at this post
#3

[eluser]whobutsb[/eluser]
[quote author="CuongVM" date="1234867285"]Hi everyone,

I have this SQL statement :

Select * from `abc_table` abc
where abc.field1 = 1 and
(
abc.field2 = 2 and
(abc.field = 3 or abc.field4 = 4)
);

If don't use $this->db->query() statement, how do I write this statement (by $this->db->where...)

Thanks for helping.[/quote]

Code:
$this->db->select('*');
$this->db->where('abc.field1', 1);
$this->db->where('abc.field2', 2);
$this->db->where('(abc.field3 = 3 OR abc.field4 = 4)');
$query = $this->db->get('abc_table')
return $query->result();

You can either write your where statement in key/value pairs like I did with fields 1 and 2 or you can write your entire where statement right in to the $this->db->where() method. Either way works just fine.

Steve
#4

[eluser]bEz[/eluser]
[quote author="whobutsb" date="1234907468"]
Code:
$this->db->select('*');
$this->db->where('abc.field1', 1);
$this->db->where('abc.field2', 2);
$this->db->where('(abc.field3 = 3 OR abc.field4 = 4)');
$query = $this->db->get('abc_table')
return $query->result();

You can either write your where statement in key/value pairs like I did with fields 1 and 2 or you can write your entire where statement right in to the $this->db->where() method. Either way works just fine.

Steve[/quote]
I think you may have missed a NESTED clause.
Code:
Select *
from `abc_table` abc
where abc.field1 = 1
    and (
        abc.field2 = 2
        and (
            abc.field = 3 or abc.field4 = 4
        )
    );
#5

[eluser]whobutsb[/eluser]
For Nested Clauses like that I would just write it as a string in to the $this->db->where() method. I don't know how to write it any other way.
#6

[eluser]bEz[/eluser]
[quote author="whobutsb" date="1234929305"]For Nested Clauses like that I would just write it as a string in to the $this->db->where() method. I don't know how to write it any other way.[/quote]
Understood, a custom string would be the natural choice for such a short (overall two clause) string.

The method you provided would have required the second and third where portions to be combined with an "AND".
Code:
$this->db->where('abc.field2 = 2 AND (abc.field3 = 3 OR abc.field4 = 4)');

OR

Code:
$this->db->where('(abc.field2 = 2 AND (abc.field3 = 3 OR abc.field4 = 4))');
notice the extra set of parenthesis
#7

[eluser]Unknown[/eluser]
Thank you very much.




Theme © iAndrew 2016 - Forum software by © MyBB