Skip to main content
edited title
Link
GDP
  • 7.7k
  • 2
  • 30
  • 72

How to combine ANDs and ORs in the WHERE clause using getQuery()a Query Object?

Source Link
GDP
  • 7.7k
  • 2
  • 30
  • 72

How to combine ANDs and ORs using getQuery()?

Given the desired SQL below, where Cond1 and Cond2 must be met OR Cond3 must be met for selection, what is the correct way to use getQuery() to achieve it?

Desired SQL: Condition1 and Condition2 within parentheses)

SELECT * FROM #__myTable 
WHERE (condition1=true AND condition2=true) OR condition3=true

With Chaining: specifying OR in the ->where()

$query = $db->getQuery(true);
$query->select('* FROM #__myTable')
->where('condition1 = true AND condition2 = true','OR')
->where('condition3 = true');

Resulting SQL: (SQL is missing parentheses)

SELECT * FROM scm_myTable
WHERE condition1 = true AND condition2 = true OR condition3 = true

With Arrays specifying OR in the ->where()

$query = $db->getQuery(true);
$conditions12 = array(
    'condition1 = true',
    'condition2 = true'
);
$conditions3 = array(
    'condition3 = true'
);
$query->select('* FROM #__myTable')
->where($conditions12, 'OR')
->where($conditions3);

Resulting SQL: (SQL is missing parentheses)

SELECT * FROM scm_myTable
WHERE condition1 = true OR condition2 = true OR condition3 = true