使用UNION ALL SQL Query获取更多值

时间:2012-01-03 23:59:53

标签: php mysql sql union-all

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

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后面添加不起作用。然后,查询不返回任何结果。

1 个答案:

答案 0 :(得分:3)

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

    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

这应该有效。