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:
id | text | secondid |
---|---|---|
1 | text1 | 123 |
2 | text2 | 321 |
3 | text3 | 222 |
4 | text4 | 101 |
second table:
id | text | origid |
---|---|---|
10 | text1 | 111 |
2 | text2 | 222 |
30 | text3 | 333 |
44 | text4 | 444 |
expected result:
id | text |
---|---|
2 | text2 |
3 | text3 |
2条答案
按热度按时间zphenhs41#
You can use a query that combines both tables
first_table
andsecond_table
using asubquery
to filter results based on certain conditions.The above query retrieves rows from
first_table
where either theid
matches the variable@Id
or where thesecondid
matches anorigid
in thesecond_table
based on the conditions specified.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.If you could possibly get the same row twice then you need to change
UNION ALL
toUNION
. Otherwise useUNION ALL
as it is more efficient.