简体   繁体   English

在多个表中选择一个不同的值(sql)

[英]Select a distinct value in multiple tables (sql)

HI, HI,

I have a database with 3 tables TAB1, TAB2, TAB3 which have exactly the same columns, for example : 我有一个包含3个表TAB1,TAB2,TAB3的数据库,它们具有完全相同的列,例如:

TAB1
cola, colb, colc, cold
TABB
cola, colb, colc, cold
...

Now I would like to search all distinct "colb" values, this is the query : 现在我想搜索所有不同的“colb”值,这是查询:

SELECT DISTINCT colb FROM TAB1

Works perfectly but now I would search all distinct "colb" values in my 3 tables "TAB1", "TAB2", "TAB3" : 工作完美但现在我会在我的3个表“TAB1”,“TAB2”,“TAB3”中搜索所有不同的“colb”值:

SELECT DISTINCT colb FROM TAB1, TAB2, TAB3

And now SQL return me an error: "Column 'colb' in field list is ambiguous" After some search, I understood that was because 'colb' column exist in my 3 tables. 现在SQL给我一个错误:“字段列表中的列'colb'是不明确的”经过一些搜索,我明白这是因为'colb'列存在于我的3个表中。

So how search in my 3 tables a distinct value from the same column ? 那么如何在我的3个表中搜索同一列中的不同值? I cannot use the LEFT JOIN because I wan to search in my all 3 tables and not in one of them. 我不能使用LEFT JOIN,因为我想搜索我的所有3个表而不是其中一个表。

Do you have an idea ? 你有想法吗 ? Thanks 谢谢

This single query with union will take care of distinct values for you. 这个带union的单个查询将为您处理不同的值。

select colb from tab1 union
  select colb from tab2 union
  select colb from tab3;
select colb from tab1 union 
select colb from tab2 union 
select colb from tab3
SELECT DISTINCT TAB1.colb,TAB2.colb,TAB3.colb FROM TAB1, TAB2, TAB3

SELECT Distinct cola from tab1 union 从tab1 union中选择Distinct cola

SELECT Distinct cola from tab2 union 从tab2 union选择Distinct cola

SELECT Distinct cola from tab3 从tab3中选择Distinct cola

In sybase, you can use the syntax that @cherouvim posted, you can imagine the subquery as a table. 在sybase中,您可以使用@cherouvim发布的语法,您可以将子查询想象为一个表。

You may also use temp tables 您也可以使用临时表

select colb into #t1 from TAB1 
insert into #t1(colb) values(select colb from TAB2) 
insert into #t1(colb) values(select colb from TAB3) 
select distinct colb from #t1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM