SQL内部联接和

时间:2015-08-08 21:22:30

标签: sql

我在使用SQL查询时遇到了一些问题...

SELECT 
    s.searchword AS searchword, 
    s.id AS id, 
    COUNT( c.id ) AS searchresult, 
    s.region AS region 

    FROM search_words AS s 

    INNER JOIN company_data AS c ON 
    c.text LIKE CONCAT(  '%', s.searchword,  '%' ) 

    AND c.region = s.region 

    GROUP BY 1 ORDER BY s.date DESC

RESULT

[{"搜索内容":"批发"" searchid":" 416""信息搜索结果&#34 ;: " 31""区域":"斯德哥尔摩"},{"搜索内容":"商业"&#34 ; searchid":" 329""信息搜索结果":" 1""区域":"斯德哥尔摩" },{"搜索内容":"医院"" searchid":" 330""信息搜索结果":&# 34; 1""区域":"斯德哥尔摩"},{"搜索内容":"运输"" searchid& #34;:" 337""信息搜索结果":" 4""区域":"斯德哥尔摩"}, {"搜索内容":"电子"" searchid":" 334""信息搜索结果":" 4""区域":"斯德哥尔摩"},{"搜索内容":"汽车"" searchid&#34 ;:" 338""信息搜索结果":" 3""区域":"斯德哥尔摩"},{& #34;搜索内容":"食物"" searchid":" 340""信息搜索结果":" 11&# 34;,&# 34;区域":"斯德哥尔摩"},{"搜索内容":"零售"" searchid":" 342& #34;"信息搜索结果":" 8""区域":"斯德哥尔摩"},{"搜索内容" :"租赁"" searchid":" 343""信息搜索结果":" 1""区域":"斯德哥尔摩"}]

这里的问题是...... region列的所有区域都有一个空值。 我也需要收集这些......正如你所看到的,它只收集斯德哥尔摩。

所以我想的是......

    SELECT 
    s.searchword AS searchword, 
    s.id AS id, 
    COUNT( c.id ) AS searchresult, 
    s.region AS region 

    FROM search_words AS s 

    INNER JOIN company_data AS c ON 
    c.text LIKE CONCAT(  '%', s.searchword,  '%' ) 

    AND c.region = s.region OR s.region = '' 

    GROUP BY 1 ORDER BY s.date DESC

但它不起作用:(

3 个答案:

答案 0 :(得分:0)

SQL中的空“值”或null s不是实际值 - 缺少它们,需要由is运算符明确处理。此外,and的优先级高于or,因此您应该拥有处理括号中region的所有条件:

SELECT 
    s.searchword AS searchword, 
    s.id AS id, 
    COUNT( c.id ) AS searchresult, 
    s.region AS region 
FROM search_words AS s 
INNER JOIN company_data AS c ON 
           c.text LIKE CONCAT(  '%', s.searchword,  '%' ) AND
           (c.region = s.region OR s.region IS NULL)
GROUP BY 1 ORDER BY s.date DESC

答案 1 :(得分:0)

如果您所在的地区可以是NULL''(空值),则这是要检查的防弹方式:

COALESCE(s.region, '') = ''

这样,您可以在与空字符串进行比较之前将NULL替换为''

答案 2 :(得分:0)

根据目前提供的信息,您可能想尝试

SELECT 
    s.searchword AS searchword, 
    s.id AS id, 
    COUNT( c.id ) AS searchresult, 
    IFNULL(s.region, 'all') AS region 
    FROM search_words AS s 
    INNER JOIN company_data AS c
      ON IFNULL(s.region, 'all') = IFNULL(c.region, 'all')
      AND c.text LIKE CONCAT(  '%', s.searchword,  '%' ) 
    GROUP BY 1, 2, 4
    ORDER BY s.date DESC
;

查看实际操作:SQL Fiddle

如果需要调整/更详细,请评论。特别是,随意调整SQL Fiddle(并提供更新版本的链接)。