SQL Server Re-querying the table with different values and adding the result

pbpqsu0x  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(118)

I have two tables. there is an input parameter. I need to perform a search on the first table, on the second table, and based on the search result on the second table, make a query to the first and output the combined result.

first step: 
select * from first table where id = 2
second step:
select * from second table where id = 2; result origid = 222
third step:
select * from first table where secondid = 222

first table:

idtextsecondid
1text1123
2text2321
3text3222
4text4101

second table:

idtextorigid
10text1111
2text2222
30text3333
44text4444

expected result:

idtext
2text2
3text3
zphenhs4

zphenhs41#

You can use a query that combines both tables first_table and second_table using a subquery to filter results based on certain conditions.

DECLARE @Id int = 2;

SELECT id, text
FROM first_table t1
WHERE id = @Id OR secondid IN (
    SELECT origid
    FROM second_table t2
    WHERE t2.id = t1.id 
);

The above query retrieves rows from first_table where either the id matches the variable @Id or where the secondid matches an origid in the second_table based on the conditions specified.

ac1kyiln

ac1kyiln2#

You could use an OR query as in the other answer. But this sometimes has performance issues. If you do encounter issues (such as a big index scan), you can use a manual Index Union instead.

DECLARE @Id int = 2;

SELECT id, text
    FROM first_table t1
    WHERE id = @Id

UNION ALL

SELECT id, text
    FROM first_table
    WHERE secondid IN (
        SELECT origid
        FROM second_table t2
        WHERE t2.id = @Id
    );

If you could possibly get the same row twice then you need to change UNION ALL to UNION . Otherwise use UNION ALL as it is more efficient.

相关问题