首页 > 解决方案 > 将 Substring_Index 与第二个表中的数据一起使用

问题描述

作为我上一个问题的后续行动:

我想选择wp_posts表中匹配的所有内容:

  1. post_type = "answer"
  2. post_type = "question"
  3. post_type 包含修订,前面是前面任一标准的 ID。例如:21-revision-v1或者10903-revision-v1我想选择那些帖子的第一个数字部分与前2个要求中选择的帖子的ID匹配的帖子。

我现在构建了一个新表ap_qa,其中包含符合上述条件 1 或 2 的帖子的所有 ID。

现在选择匹配条件 3 的案例,我认为使用Substring_Index()as 允许在字符串中进行匹配。

我目前的代码是:

SELECT * 
FROM `wp_posts` p 
WHERE p.post_type IN ('answer', 'question') OR
Substring_Index(p.post_Type,'-revision',1) IN QA.ID

where 之后的第一条规则是满足条件 1 和 2,最后一行是满足条件 3。但是我的语法无效,如返回。

错误消息显示(荷兰语):

#1064 - Er is iets fout in de gebruikte syntax bij 'QA.ID' in regel 4

标签: mysqlsqlselectsubquerywhere-clause

解决方案


我现在构建了一个新表 ap_qa,其中包含来自符合上述条件 1 或 2 的帖子的所有 ID。

你根本不需要一个临时表。您可以在单个查询中直接从原始表中获得所需的结果:

select *
from wp_posts wp
where post_type in ('answer', 'question') and exists (
    select 1
    from wp_posts wp1
    where 
        wp1.post_type in ('answer', 'question') 
        or wp1.id = substring_index(wp.post_type, '-revision', 1)
)

推荐阅读