java - 匹配来自两个不同表的两列的字符串

标签 java mysql database postgresql jdbc

我创建了两个表,我们将它们称为表 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 对应的最高排名的描述时遇到问题。我希望这是有道理的!请让我知道添加更多信息。

最佳答案

您可以使用运算符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          |

关于java - 匹配来自两个不同表的两列的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59687877/

相关文章:

java - 将数组对象传递给 jdbc 查询

php - MySQL 仅当该记录的日期时间列数据发生更改时才更新该数据

php - 在这种情况下如何使用 UNION (MySQL)

java - 我可以将表名作为参数传递给 java 准备语句吗?

mysql - 将电子邮件 VARCHAR(320) 存储为 UNIQUE,#1071 - 指定的键太长;最大 key 长度为 767

MySQL:低基数/选择性列=如何索引?

java - 单条数据库记录插入失败是否需要回滚?

java - 使用 Jest 或 Java API 有没有办法告诉 Elasticsearch 从 json 创建文档作为字符串?

java - 私有(private)成员变量在 dispatchTouchEvent 中的 Nexus 5x 上变为空

java - Spring 批处理 : Skip a record that cannot be written to the database and proceed with the next record