选择一个特定数据行(必需)和另外3个(必须包含特定数据行)

时间:2015-04-02 13:37:02

标签: postgresql

我需要选择一个特定行和另外两行不是特定行(总共3行)。特定行必须始终包含在3个结果中。我该怎么办呢?我认为可以使用UNION ALL完成,但我还有其他选择吗?谢谢大家! :)

以下是我创建示例表的脚本:

create table users (
    user_id serial primary key,
    user_name varchar(20) not null
);

create table result_table1 (
    result_id serial primary key,
    user_id int4 references users(user_id),
    result_1 int4 not null
);

create table result_table2 (
    result_id serial primary key,
    user_id int4 references users(user_id),
    result_2 int4 not null
);

insert into users (user_name) values ('Kevin'),('John'),('Batman'),('Someguy');
insert into result_table1 (user_id, result_1) values (1, 20),(2, 40),(3, 70),(4, 42);
insert into result_table2 (user_id, result_2) values (1, 4),(2, 3),(3, 7),(4, 5);

这是我的UNION查询:

SELECT  result_table1.user_id,
        result_1,
        result_2

FROM    result_table1

INNER JOIN (
    SELECT  user_id

    FROM    users
) users 
ON users.user_id = result_table1.user_id

INNER JOIN (
    SELECT  result_table2.user_id,
            result_2

    FROM    result_table2
) result_table2 
ON result_table2.user_id = result_table1.user_id

WHERE   users.user_id = 1

UNION ALL

SELECT  result_table1.user_id,
        result_1,
        result_2

FROM    result_table1

INNER JOIN (
    SELECT  user_id

    FROM    users
) users 
ON users.user_id = result_table1.user_id

INNER JOIN (
    SELECT  result_table2.user_id,
            result_2

    FROM    result_table2
) result_table2 
ON result_table2.user_id = result_table1.user_id

WHERE   users.user_id != 1

LIMIT 3;

除了UNION之外还有其他选择吗?该查询可以正常工作并执行我想要的操作,但是如果我有一组更大的行(假设user_id = 1将始终存在),它是否总是包含user_id = 1? :(

谢谢大家! :)

0 个答案:

没有答案