如何使用查询对象在WHERE子句中组合AND和OR?


21

给定以下所需的SQL,必须满足Cond1 Cond2 必须满足Cond3的选择,才可以使用正确的方法getQuery()来实现?

所需的SQL: 括号中的Condition1和Condition2)

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

使用链接: 在-> where()中指定OR

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

结果SQL:(SQL缺少括号)

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

使用 在-> where()中指定OR的数组

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

结果SQL:(SQL缺少括号)

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

Answers:


20

通过Chaining,包括所需的括号,可以生成所需的SQL:

使用链接: 指定“或”并将Cond1 / 2包装在括号中

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

产生的SQL :(包括括号)

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

或使用orWhere / andWhere

$query = $db->getQyery(true);
$query->select('*')
->from($db->quoteName('#__myTable'))
->where($db-quoteName('condition3') . ' = TRUE')
->orWhere(array($db->quoteName('condition1') . ' = TRUE', $db->quoteName('condition2') . ' = TRUE'));
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.