我正在尝试为以下内容编写查询...
SELECT SQL_CALC_FOUND_ROWS * FROM calls
WHERE id IS NOT NULL
AND account_name LIKE '%$account_search%'
AND name LIKE '%$adv_term_det%' OR description LIKE '%$adv_term_det%'
AND type != 'online'
AND marked_completed_by = ''
ORDER BY $sort_by DESC LIMIT $page_position, $item_per_page
但结果并非预期值。我怀疑引起问题的那条线是..
AND name LIKE '%$adv_term_det%' OR description LIKE '%$adv_term_det%'
我怀疑它应该是一个子查询,但经过多次尝试使用IN后,我还没有能够使它工作。
SELECT SQL_CALC_FOUND_ROWS * FROM calls
WHERE call_ref IN
(SELECT call_ref FROM calls
WHERE name LIKE '%$adv_term_det%' OR description LIKE '%$adv_term_det%'
)
AND id IS NOT NULL
AND account_name LIKE '%$account_search%'
AND type != 'online'
AND marked_completed_by = ''
ORDER BY $sort_by DESC LIMIT $page_position, $item_per_page;
基本上我想要返回符合所有其他条件的所有记录,并且$adv_term_det
或name
中都有description
。
如果我只使用AND name LIKE '%$adv_term_det%'
,我会得到我对该查询所期望的结果,同样如果我只使用AND description LIKE '%$adv_term_det%'
,但我需要找到包含%$adv_term_det%'
的记录name
或description
答案 0 :(得分:1)
要么您对复杂的布尔逻辑不是很熟悉,要么就是错过了错误。在任何一种情况下,我都建议您使用括号,特别是在混合AND
和OR
时。我认为这是你想要的逻辑:
WHERE (id IS NOT NULL) AND
(account_name LIKE '%$account_search%') AND
(name LIKE '%$adv_term_det%' OR description LIKE '%$adv_term_det%') AND
(type <> 'online') AND
(marked_completed_by = '')
另请注意,将变量直接插入SQL字符串是危险的。您应该为此目的使用参数。