如何在多个表中选择唯一折扣

时间:2015-11-02 05:42:45

标签: mysql sql

我有5张桌子。我想使用MYSQL找到所有5个表的唯一折扣值。

表的形式是:

table1(userid,discount)  
table2(userid,discount)    
table3(userid,discount)    
table4(userid,discount)    
table5(userid,discount)

4 个答案:

答案 0 :(得分:1)

您可以使用UNION来实现此目标。

UNION的默认行为是从结果中删除重复的行。可选的DISTINCT关键字除了默认值之外没有任何效果,因为它还指定了重复行删除。

使用可选的ALL关键字,不会发生重复行删除,结果包含所有SELECT语句中的所有匹配行。

<强>查询

select discount from table1
union
select discount from table2
union
select discount from table3
union
select discount from table4
union
select discount from table5;

如果你想从上面的sql查询中对结果进行排序,你可以使用下面的ORDER BY

<强>查询

select t.discount from
(
    select discount from table1
    union
    select discount from table2
    union
    select discount from table3
    union
    select discount from table4
    union
    select discount from table5
)t
order by t.discount;

按照您的要求按降序或升序排序。

答案 1 :(得分:0)

使用MySQL union

select * from (
    select * from table1
    union
    select * from table2
    union
    select * from table3
    union
    select * from table4
    union
    select * from table5
)new group by new.discount

答案 2 :(得分:0)

结合distinct和union

Select distinct discount from
(SELECT discount from table1
Union
Select discount from table2
Union
Select discount from table3
Union
Select discount from table4
Union
Select discount from table5) As tview

答案 3 :(得分:0)

试试这种方式

select distinct discount from (
select userid,discount from table1
union 
select userid,discount from table2
union 
select userid,discount from table3
union 
select userid,discount from table4
union 
select userid,discount from table4)a