简体   繁体   English

在多个OR条件下联接2个表

[英]Joining 2 tables on multiple OR conditions

What I want to accomplish: I want to join 2 tables on urls. 我想完成的工作:我想在URL上加入2个表。 But one table has url formats that are a bit different from the other. 但是一个表的url格式与另一个表有些不同。 As they are the only common denominator between the two tables, (no unique id's to join on) I have to use wildcards to match the url's. 因为它们是两个表之间的唯一共同点,所以(必须加入唯一的ID)我必须使用通配符来匹配URL。

For example one table has formats like these: 'www.url.com', 'url.com.', 'abc.def.url.com' while another table has format 'url.com' So in order to match I need to do something like 例如,一个表的格式如下:“ www.url.com”,“ url.com。”,“ abc.def.url.com”,而另一表的格式为“ url.com”,因此为了匹配我需要做类似的事情

LEFT JOIN t1
ON t1.url = '%.'||t2.url OR t1.url= t2.url||'.' OR etc...

Is this the right way to approach this? 这是解决这个问题的正确方法吗?

I'm using PostgreSQL. 我正在使用PostgreSQL。

You have a very strict constraint as you are joining on URLs. 在加入URL时,您有一个非常严格的约束。 url.com should match url.com and www.url.com should match url.com but www.dummyurl.com shouldnt match www.myurl.com. url.com应该匹配url.com,而www.url.com应该匹配url.com,但是www.dummyurl.com不应该匹配www.myurl.com。 Your original query is fine and is the right way to approach the problem. 您的原始查询很好,并且是解决此问题的正确方法。

To avoid overmatching, would recommend using this 为避免过度匹配,建议使用

select * from t1 inner join t2
on t1.url like '%.'||t2.url or t1.url = t2.url 

I have used inner join to avoid NULL matching Here's a demo 我使用了内部联接来避免NULL匹配 这是一个演示

This assumes that t2.url will be at the end of t1.uel after a period or both strictly match. 假设t2.url在一个句点或两者严格匹配之后将位于t1.uel的末尾。 Try running this and see if you get your anticipated results 尝试运行此命令,看看是否获得预期的结果

Just a guess, can you use CONTAINS()? 只是一个猜测,您可以使用CONTAINS()吗?

LEFT JOIN t1
ON CONTAINS(t1.url, t2.url)

Edit: Well, seems that PostGRE doesn't support CONTAINS. 编辑:嗯,似乎PostGRE不支持CONTAINS。

Try using position() function. 尝试使用position()函数。 It returns 0 if the substring is not found 如果未找到子字符串,则返回0

ON position(t2.url in t1.url) <> 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM