SQL查询 - 确定哪个逻辑运算符为true

时间:2013-09-22 02:49:13

标签: mysql sql select

我有一个SQL查询,使用一堆OR x = y语句检查表中是否已存在多个给定值之一。然后我对结果进行行计数。

$exists = db_query("SELECT * FROM {leads_client} WHERE (companyName = '".$form_state['values']['company_name']."' 
                        OR billingEmail = '".$form_state['values']['billing_email']."' 
                        OR leadEmail = '".$form_state['values']['lead_email']."'
                        OR contactEmail = '".$form_state['values']['contact_email']."'
                        OR url = '".$form_state['values']['company_url']."') AND NOT 
                        clientId = '".$clientId."'");

    if($exists->rowCount() > 0){
          //Do something
    }

确定哪些OR语句是真的最简洁的方法是什么,而不将其分解为多个查询?

3 个答案:

答案 0 :(得分:1)

您的网站容易受到SQL注入攻击。您需要立即阅读本文并修复所有数据库查询才能正确使用参数。

Drupal编写安全代码: https://drupal.org/writing-secure-code

Drupal数据库访问: https://drupal.org/node/101496

答案 1 :(得分:1)

您可以在选择中进行原始比较:

SELECT *, 
    companyName = '".$form_state['values']['company_name']."' AS companyNameMatch,
    billingEmail = '".$form_state['values']['billing_email']."' AS billingEmailMatch,
    ...
FROM {leads_client} 
WHERE (companyName = '".$form_state['values']['company_name']."' 
       OR billingEmail = '".$form_state['values']['billing_email']."' 
       OR leadEmail = '".$form_state['values']['lead_email']."'
       OR contactEmail = '".$form_state['values']['contact_email']."'
       OR url = '".$form_state['values']['company_url']."') AND NOT clientId = '".$clientId."'");

这将返回如下结果集:

|------------------|-------------------|
| companyNameMatch | billingEmailMatch |
|------------------|-------------------|
| 0                | 1                 |
|------------------|-------------------|

通过这种方式,您可以通过1的列知道哪个匹配。

答案 2 :(得分:0)

您可以添加CASE语句来跟踪符合的条件,例如:

SELECT *
      ,CASE WHEN companyName = '".$form_state['values']['company_name']."' THEN 'condition1'
            WHEN billingEmail = '".$form_state['values']['billing_email']."' THEN 'condition2'
            ...
       END
FROM {leads_client} 
WHERE (companyName = '".$form_state['values']['company_name']."' 
       OR billingEmail = '".$form_state['values']['billing_email']."' 
       OR leadEmail = '".$form_state['values']['lead_email']."'
       OR contactEmail = '".$form_state['values']['contact_email']."'
       OR url = '".$form_state['values']['company_url']."') AND NOT 
                        clientId = '".$clientId."'");