首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >mySQL -如何正确编码SELECT语句

mySQL -如何正确编码SELECT语句
EN

Stack Overflow用户
提问于 2016-12-07 16:05:19
回答 2查看 69关注 0票数 1

我有一条mySQL SELECT语句,在WHERE条件中结合了全文搜索和普通搜索,还有一个类似下面这样的JOIN

代码语言:javascript
复制
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

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

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

编辑:

在以前的版本中,我使用了以下语句

代码语言:javascript
复制
 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列时,代码很容易爆炸,这是我想要避免的。

欢迎更多的想法和帮助

EN

回答 2

Stack Overflow用户

发布于 2016-12-07 16:14:22

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

代码语言:javascript
复制
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比较。

票数 0
EN

Stack Overflow用户

发布于 2016-12-07 16:37:22

我的解决方案是,如果默认值为'',则使用CASE WHEN将其设置为countries.name

代码语言:javascript
复制
(CASE WHEN countries.name is null then 'default value' else countries.name END)

新建查询

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41012233

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档