2

我正在使用此查询从两个表中获取结果:

SELECT * FROM (
    SELECT parent_id as mID, count(*) as cnt
        FROM wp_forum_posts
        WHERE text LIKE '%{$word}%'
        GROUP by 1
        UNION ALL
            SELECT id, count(*)
            FROM wp_forum_threads
            WHERE subject LIKE '%{$word}%'
            GROUP by 1) x
ORDER BY 2, 1

我想从中选择更多值wp_forum_threads。之类的值subject。我怎样才能做到这一点?简单地在后面添加id是行不通的。那么查询不返回任何结果。

4

1 回答 1

3

UNION ALL 两部分的select 中的列数应该相同。这意味着,例如,如果您想在查询的第二部分添加“主题”,则需要在查询的第一部分添加一个“占位符”:

    SELECT * FROM (
SELECT parent_id as mID, NULL, count(*) as cnt
    FROM wp_forum_posts
    WHERE text LIKE '%{$word}%'
    GROUP by 1
    UNION ALL
        SELECT id, subject, count(*)
        FROM wp_forum_threads
        WHERE subject LIKE '%{$word}%'
        GROUP by 1) x
ORDER BY 2, 1

这应该有效。

于 2012-01-04T00:47:13.187 回答