我有一个自定义sql查询,可以从特定类别(ID=62)中获取最新帖子。看起来是这样的:
SELECT p.ID,
u.display_name AS author,
post_date_gmt,
post_title,
p.post_author AS author_id,
rel.term_taxonomy_id,
(SELECT guid
FROM wp_BOMEGAposts
WHERE id = m.meta_value) AS image,
(SELECT term_taxonomy_id
FROM wp_BOMEGAterm_relationships
WHERE object_id = p.ID) AS categories
FROM wp_BOMEGAposts p
LEFT JOIN wp_BOMEGAusers u ON p.post_author = u.ID
LEFT JOIN wp_BOMEGApostmeta m ON p.ID = m.post_id
INNER JOIN wp_BOMEGAterm_relationships rel ON p.ID = rel.object_id
WHERE p.post_type = \'post\'
AND p.post_status = \'publish\'
AND m.meta_key = \'_thumbnail_id\'
AND rel.term_taxonomy_id IN (62)
ORDER BY p.post_date DESC
LIMIT 1
OFFSET 0
这篇文章有多个类别,我想得到它们。所以我写了一个子查询来修改它们。但我有个错误:
#1242-子查询返回超过1行
我怎样才能解决这个问题?
最合适的回答,由SO网友:mozboz 整理而成
看起来这是导致问题的查询的新部分,对吗?
(SELECT term_taxonomy_id
FROM wp_BOMEGAterm_relationships
WHERE object_id = p.ID) AS categories
如果是这样,则错误消息很清楚:此查询中的子选择只应返回一行。如果它返回多个行,它不知道如何将所有这些行混合到查询其余部分的一行中。
因此,您需要找到一种方法将此子查询的所有行连接到一行中,并使用SQL命令GROUP_CONCAT
会这样做的
您希望使子查询类似于:
(SELECT GROUP_CONCAT(term_taxonomy_id)
FROM wp_BOMEGAterm_relationships
WHERE object_id = p.ID) AS categories
如果要返回多个term\\u taxonomy\\u id,则它们将以逗号分隔的单行形式返回,如:
10,50,100
所以你需要弄清楚你想用这些做什么。