简体   繁体   English

使用like运算符进行内部联接SQL

[英]Inner join SQL with like operator

I have my main table that has a column for a search query. 我的主表有一个用于搜索查询的列。 A simplified example: 一个简化的例子:

Querytable 查询表

id   query
1    hello new york
2    no information here
3    madison festival 

Geotable 地理表

id   suburb     postcode
11    new york   123
12    brooklyn   345
13    madison    999

If the search query has a location, I want to retrieve the postcode in a sample result as follows: 如果搜索查询中有一个位置,我想在样本结果中检索邮政编码,如下所示:

id     query             suburb      postcode
1      hello new york    new york    123
3      madison festival  madison     999

I'm at the moment doing this via SQL and returns the desired result (almost: with errors like if `inform' is a suburb it will be retrieved although we want to match full words). 目前,我正在通过SQL进行操作并返回所需的结果(几乎是这样:如果我们想匹配完整的单词,则会出现类似“ inform”是一个郊区的错误,但它将被检索到)。

SELECT QT.id, query, suburb, postocde
FROM Querytable as QT
INNER JOIN Geotable ON query LIKE concat('%',suburb,'%');

Since the above tables are large how can I improve this query? 由于上面的表很大,我该如何改进此查询? Or is there a better way to tackle this problem? 还是有更好的方法来解决这个问题?

from your table, i think the JOIN should be on column ID and your LIKE should be in WHERE, not in JOIN. 从您的表中,我认为JOIN应该在列ID上,您的LIKE应该在WHERE而不是JOIN中。 so something like this instead 所以像这样

SELECT QT.id, query, suburb, postocde
FROM Querytable as QT
INNER JOIN Geotable GT ON QT.id=GT.id 
WHERE query LIKE concat('%',suburb,'%');

but even with that, if `inform' is a suburb it will be retrieved since it match the like '%inform%' condition. 但是即使这样,如果“ inform”是一个郊区,由于它与类似“%inform%”的条件相匹配,也会被检索。 do you have index in that table to improve performance? 您在该表中有索引以提高性能吗? in which column you put the indexes? 您将索引放在哪一列?

I did some changes in your query and gives the desired result for me. 我对您的查询做了一些更改,并为我提供了所需的结果。 Try this. 尝试这个。

SELECT QT.id, query, suburb, postcode
FROM Querytable as QT
INNER JOIN Geotable ON concat(query,Space(1)) LIKE concat('%',suburb,'[ ]%')

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

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