mySQL - 如何正确编写SELECT语句

时间:2016-12-07 08:05:19

标签: mysql

我有一个mySQL SELECT语句,其中包含WHERE条件下的全文搜索和普通搜索,以及另外一个JOIN这样的

SELECT 
 customer.*, 
 countries.name as country
 FROM customer  
 LEFT JOIN countries ON countries.ID = customer.country_id 
 WHERE customer.num   = :keyword 
    OR customer.city  = :keyword  
    OR customer.email = :keyword 
    OR MATCH (customer.company) AGAINST (:keyword)
    OR countries.name = :keyword

只要table.column (customer.company)no result条件的一部分,对countries.name列进行全文搜索的查询就会返回WHERE。但是对countries.name本身的查询是成功的。

如何使用上面示例中所有WHERE组件的组合正确编码SELECT语句以返回成功的查询?

编辑:

在之前的版本中,我使用了这个声明

 SELECT 
  customer.* ,
  countries.name
  FROM customer, countries 
  WHERE customer.country_id=countries.ID 
  AND MATCH (customer.company) AGAINST (:keyword)

  UNION

  SELECT 
  customer.*, 
  countries.name
  FROM customer, countries 
  WHERE customer.country_id=countries.ID 
  AND countries.name=:keyword

运作良好。我只是不知道这是否是使用不同搜索(全文和普通)查询两个表的有效方法。此外,当我搜索超过2列时,代码很容易被炸毁,我想避免。

欢迎任何更多的想法和帮助

2 个答案:

答案 0 :(得分:0)

您应该检查NULLs,因为您使用的是LEFT JOIN

SELECT 
     customer.*, 
     countries.name as country
 FROM customer  
 LEFT JOIN countries ON countries.ID = customer.country_id 
 WHERE customer.num   = :keyword 
    OR customer.city  = :keyword  
    OR customer.email = :keyword 
    OR MATCH (customer.company) AGAINST (:keyword)
    OR (countries.name = :keyword OR countries.name IS NULL)

为了澄清,LEFT JOIN右表上的条件只应放在ON子句内,而不是WHERE子句中。这有点不同,因为您要将其与所有其他条件进行比较,因此 - NULL比较。

答案 1 :(得分:0)

我的解决方案只是设置默认值= countries.nameCASE WHEN如果它使用(CASE WHEN countries.name is null then 'default value' else countries.name END)

为空
SELECT 
 customer.*, 
 countries.name as country
 FROM customer  
 LEFT JOIN countries ON countries.ID = customer.country_id 
 WHERE customer.num   = :keyword 
    OR customer.city  = :keyword  
    OR customer.email = :keyword 
    OR MATCH (customer.company) AGAINST (:keyword)
    OR (CASE WHEN countries.name is null then '' else countries.name END) = :keyword

新查询

io.of('/').sockets[rcvrId].emit('message', data)