簡體   English   中英

查詢多個表並將結果合並到一個用於存儲過程的返回表中?

[英]query multiple tables and combine results into one return table for stored procedure?

我有幾個不同的表,但它們都有2個相同名稱的列。 我想編寫一個存儲過程,該過程搜索所有表中的一列並返回結果。 有想法嗎? 在SQL方面,我還算不上什么。

您要查找的操作是UNIONUNION ALL

SELECT * FROM (
 SELECT col1, col2 FROM table1
 UNION ALL
 SELECT col1, col2 FROM table2
 UNION ALL
 SELECT col1, col2 FROM table3
) all_tables
WHERE all_tables.col1 = 'something'

如果使用UNION而不是UNION ALL ,數據庫將消除可能在多個表中重復的行。 如果您知道不會有任何重復,請使用UNION ALL因為它通常要快得多。

Select myColumn FROM Table1
UNION Select myColumn FROM Table2
UNION Select myColumn FROM Table3 

..等等

-注意所有列名必須相同並且必須在每個表中才能正常工作

您甚至不需要存儲過程...只需使用聯合查詢即可。

select field1, field2 from table1 where table1.field1=criteria
union
select field1, field2 from table2 where table2.field1=criteria
union
select field1, field2 from table3 where table3.field1=criteria
etc...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM