【问题标题】:Matching Strings from two columns from two different tables匹配来自两个不同表的两列的字符串
【发布时间】:2020-04-28 11:16:21
【问题描述】:

我创建了两个表,我们称它们为表 a 和表 b。

表 A 由一列称为 domainType 的字符串组成

表 B 由一列字符串组成,这些字符串是表 A 列的子字符串(称为 topLevelDomain)

CREATE TABLE a ( rank int, name text, domainType text )

CREATE TABLE b ( topLevelDomain text, domainDescription text)

表a:

 rank     name      domainType
 1        a          com
 2        b          co jp
 3        c          co cn

表b:

topLevelDomain    domainDescription
com               country1
in                country2
cn                country3
...
jp                country30

我想根据 domainType 的排名列出最流行的描述(国家) 显示这个:

想要的结果:

country1 -------> since rank is 1 (in table a)
country30 ------> since rank is 2 (in table a)
country2 --------> since rank is 3 (in table a)

我在将 topLevelDomain 列与 domainType 列“关联”并返回与 domainType 对应的最高排名的描述时遇到问题。我希望这是有道理的!请让我知道添加更多信息。

【问题讨论】:

    标签: java mysql database postgresql jdbc


    【解决方案1】:

    您可以使用运算符LIKE 加入表格:

    select b.domaindescription
    from b left join a
    on  concat(' ', a.domaintype, ' ') like concat('% ', b.topleveldomain, ' %')
    order by case when a.domaintype is null then 1 else 0 end, a.rank
    

    请参阅demo
    结果:

    | domaindescription |
    | ----------------- |
    | country1          |
    | country30         |
    | country3          |
    | country2          |
    

    【讨论】:

    • 感谢您的回答!! concat 部分确实有帮助,但是,当涉及 ORDER BY 部分时,我收到以下错误:“错误:对于 SELECT DISTINCT,ORDER BY 表达式必须出现在选择列表中”。
    • 你可以查看demo中没有这个错误的地方。
    • 我遵循了相应的演示,但是当我尝试执行它时,它指出“在此 ResultSet 中找不到列名 topLevelDomain。” EDIT 小错误,全部修复!!
    猜你喜欢
    • 1970-01-01
    • 2015-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-21
    • 2020-10-21
    相关资源
    最近更新 更多