MYSQL具有最小值的许多表的不同值

问题描述 投票:1回答:4

我有三张产品表:

table1:producer_code,price,company

table2:producer_code,price,company

table3:producer_code,price,company

现在我想列出我可以做的产品(与所有表不同):

select distinct producer_code, price, company
from (
    select producer_code, price, company FROM table1
    union all
    select producer_code, price, company FROM table2
    union
    select producer_code, price, company FROM table3
) tmp_table

但如何列出最便宜的产品?示例:如果相同的产品将在三个表中,我希望它只听一次,但是从最便宜的来源(公司专栏)。我应该使用工会还是加入?

mysql sql database select
4个回答
2
投票
select distinct producer_code, min(price), company
from (
    select producer_code, price, company FROM table1
    union all
    select producer_code, price, company FROM table2
    union all
    select producer_code, price, company FROM table3
) tmp_table
group by producer_code,company

1
投票

使用min可以获得最小的值。

我想你可能会使用UNION ALL

select producer_code, MIN(price), company
from (
    select producer_code, price, company FROM table1
    union all
    select producer_code, price, company FROM table2
    union all
    select producer_code, price, company FROM table3
) tmp_table
GROUP BY producer_code,company

1
投票

你可以使用qazxsw poi获得如下:

Min

1
投票

我认为OP需要来自各种公司的最便宜的价格,并且存储在多个桌子上。

附表:

select producer_code, Min(price), company
from (
    select producer_code, price, company FROM table1
    union all
    select producer_code, price, company FROM table2
    union
    select producer_code, price, company FROM table3
) tmp_table
group by tmp_table.producer_code, tmp_table.company

我们需要在这里加入2套。一个是实际组合集A,另一个是具有producer_code和最低价格的集合。

create table table1(producer_code varchar(50), price decimal(18,2), company varchar(100));
create table table2(producer_code varchar(50), price decimal(18,2), company varchar(100));
create table table3(producer_code varchar(50), price decimal(18,2), company varchar(100));

insert into table1
select 'ITEM001', 45, 'Company A' 
UNION ALL
select 'ITEM002', 200, 'Company B'
UNION ALL
select 'ITEM003', 150, 'Company B';

insert into table2
select 'ITEM001', 50, 'Company B'
UNION ALL
select 'ITEM002', 300, 'Company C'
UNION ALL
select 'ITEM003', 55, 'Company D';

insert into table3
select 'ITEM001', 190, 'Company F'
UNION ALL
select 'ITEM002', 78, 'Company G'
UNION ALL
select 'ITEM003', 100, 'Company A';

结果:

select 
A.* from 
(
SELECT * FROM table1
UNION 
SELECT * FROM table2
UNION 
SELECT * FROM table3
)A
INNER JOIN
(
    SELECT producer_code, min(price) AS price FROM (
    SELECT * FROM table1
    UNION ALL
    SELECT * FROM table2
    UNION ALL
    SELECT * FROM table3
    )B
    GROUP BY producer_code
)CHEAP ON A.producer_code = CHEAP.producer_code AND A.price = CHEAP.price;
© www.soinside.com 2019 - 2024. All rights reserved.