使用 Substring_Index 第二个 table 的数据

Using Substring_Index with data from a second table

作为我的 的跟进:

我想要 select wp_posts table 中匹配的所有内容:

  1. post_type = "answer"
  2. post_type = "question"
  3. post_type 包含修订,前面是前面任一条件的 ID。例如:21-revision-v110903-revision-v1 我想要 select 那些第一个数字部分与前 2 个要求中 selected 的帖子 ID 相匹配的帖子。

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

现在 select 匹配条件 3 的情况,我考虑使用 Substring_Index(),因为它允许在字符串中进行匹配。

我当前的代码是:

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

如您的错误消息所示,您的 systqax 是错误的 使用 zhis

之类的东西
SELECT * 
FROM `wp_posts` p 
WHERE p.post_type IN ('answer', 'question') 
OR
 QA.ID LIKE CONCAT(Substring_Index(p.post_Type,'-revision',1) ,'%')
LIMIT 0, 25

您需要一个子查询 returns table ap_qa:

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

或没有 table ap_qa:

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

I now constructed a new table ap_qa which holds all the ID's from posts matching either criteria 1 or 2 above.

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

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)
)