Sql 连接两个表而不使用公共键的正确方法,并在不匹配时保留空值

Sql 连接两个表而不使用公共键的正确方法,并在不匹配时保留空值,sql,join,google-bigquery,conditional-statements,Sql,Join,Google Bigquery,Conditional Statements,我是sql新手,意识到这可能不是火箭科学,但我有两个表,第一个表有一个变量title_name,我想从中提取主题(不能使用regex,因为位置不同),第二个表是一个具有正确对应关系的查找表 表1 书名(例如:英国图书语言) 表2 旧主题(例如:英雄幻想) 新主题(示例:幻想) 这是我到目前为止提出的,但是这个查询只保留匹配的行。 如果没有匹配项,我怎么说我想要一个新主题的“(未设置)”值 select theme_new, from Table_1, Table_2 where title_n

我是sql新手,意识到这可能不是火箭科学,但我有两个表,第一个表有一个变量title_name,我想从中提取主题(不能使用regex,因为位置不同),第二个表是一个具有正确对应关系的查找表

表1

书名(例如:英国图书语言)

表2

旧主题(例如:英雄幻想)

新主题(示例:幻想)

这是我到目前为止提出的,但是这个查询只保留匹配的行。 如果没有匹配项,我怎么说我想要一个新主题的“(未设置)”值

select
 theme_new,
from Table_1, Table_2
where title_name like concat('%',theme_old ,'%')
我非常感谢您的帮助,我尝试过的方法到目前为止都不起作用。

我想您应该使用一种新的方法

像这样的东西

select
CASE 
    WHEN title_name like concat('%',theme_old ,'%') THEN theme_new 
    ELSE '(not set)' 
END
from Table_1, Table_2

您想要一个
左连接

select theme_new
from Table_1 t1 left join
     Table_2
     on t2.title_name like concat('%', t2.theme_old , '%')
也就是说,我不确定BigQuery是否支持这种语法

您可能需要使用:

select t1.title_name, array_agg(theme_new ignore nulls)
from (select t1.title_name, theme_new,
      from Table_1 t1 cross join
           Table_2
      where t2.title_name like concat('%', t2.theme_old , '%')
      union all
      select t1.title_name, null
      from table_1 t1
     ) t1
group by t1.title_name;

非常感谢,第一个选项对bq确实不起作用。@Thaid。第二个呢?在BQ中,带不等式条件的外连接是很棘手的。非常感谢。这能回答你的问题吗?