我一直在尝试使用包含公共子字符串的列连接两个MYSQL表。
我的第一个表trim_table
是子字符串及其id的数据集。每行包含一个id和一个子串,例如“1717 WINTON DR”。
第二个表wp_prop
包含一列field_313
,可能包含第一个表中找到的子字符串。 field_313的示例值为“THE SARGENT III @ 1717 WINTON DR”
以下是我为加入两个表而制定的查询:
SELECT *, wp_prop.id as prop_id, trim_table.id as post_id, wp_prop.field_313
as prop_name, trim_table.trim_value as post_name
FROM
(SELECT id, TRIM(SUBSTRING(post_title, LOCATE('@', post_title)+1)) as trim_value
FROM wp_nd333j_posts WHERE post_type="fplan") as trim_table
JOIN
wp_nd333j_wpl_properties as wp_prop
ON trim_table.trim_value LIKE CONCAT('%', wp_prop.field_313, '%')
不幸的是,查询不会返回任何行。我已将查询分解为不同的部分以验证它们是否有效。
可以肯定的是,子串数据集通过执行以下查询返回正确的行:
SELECT * FROM
(SELECT id, TRIM(SUBSTRING(post_title, LOCATE('@', post_title)+1)) as trim_value FROM wp_nd333j_posts WHERE post_type="fplan") as trim_table
我还可以通过执行以下查询来验证我的wp_prop
表是否包含与我上面发布的示例类似的子字符串:
SELECT * FROM wp_nd333j_wpl_properties as wp_prop WHERE field_313 LIKE "%1717 WINTON DR%"
我还通过执行查询验证了我的子串数据集包含我想要的子串:
SELECT * FROM
(SELECT id, TRIM(SUBSTRING(post_title, LOCATE('@', post_title)+1)) as trim_value FROM wp_nd333j_posts WHERE post_type="fplan") as trim_table
WHERE trim_value = "1717 WINTON DR"
答案 0 :(得分:2)
您只需在ON
子句中切换字段:
ON wp_prop.field_313 LIKE CONCAT('%', trim_table.trim_value, '%')
http://sqlfiddle.com/#!9/616a0/1
SELECT
trim_table.id as post_id,
trim_table.trim_value as post_name,
wp_prop.id as prop_id,
wp_prop.field_313 as prop_name
FROM (
SELECT id,
TRIM(SUBSTRING(post_title, LOCATE('@', post_title)+1)) as trim_value
FROM wp_nd333j_posts
WHERE post_type="fplan"
) as trim_table
INNER JOIN
wp_nd333j_wpl_properties as wp_prop
ON wp_prop.field_313 LIKE CONCAT('%', trim_table.trim_value, '%')