2017-05-09 4 views
0

私は2つのテーブルを持っています。他のテーブルに近い値のテーブルを更新する

Products 
------------ 

ID | Sales | Rank 
================== 
1 | 0  | 100 
2 | 0  | 105 
3 | 0  | 200 
4 | 0  | 900 

Sales 

ID | Sales | Rank 
================== 
1 | 2000  | 99 
2 | 5000  | 106 
3 | 8000  | 800 
4 | 2500  | 950 

sales.productsをランクに基づいてsales.salesに更新したいとします。例えば

set products.sales=sales.sales where sales.sales is nearest to product.sales 

上記の場合は、クエリの結果になります。

Products 
------------ 

ID | Sales | Rank 
================== 
1 | 2000  | 100 
2 | 5000  | 105 
3 | 5000  | 200 
4 | 2500  | 900 

見つからない場合は、Product.Rankがsales.rankに最も近い値である何かを見つける、ランクに基づいて売上表からの製品の販売を探してみてください。

おかげ

+0

https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-を参照してください。非常にシンプルなSQLクエリ – Strawberry

+0

'set products.sales = sales.sales、sales.rankはproduct.rankに最も近いところにあります。 ' –

+0

はい、それは私が探しているものです。 – formul1

答えて

0

MySQLは、ウィンドウ機能を持っていないので、あなたはそれを「苦労」を行う必要があります。 、その差がランクを見つけ、再び参加し、すべてが、最高salesを破棄することにより、最も近いどのランクを見つけるためにそれを使用すると

select p.rank, min(abs(s.rank - p.rank)) diff 
from sales s 
cross join products p 
group by 1 

:まず、最小差は、各製品ランク何のためにあるのかを計算クエリを作成ネクタイ破る:SQLFiddleは、カウントのためにダウンしているので

update Products 
join (select p.rank, min(abs(s.rank - p.rank)) diff 
    from Sales s 
    cross join Products p 
    group by 1) x on Products.rank = x.rank 
join Sales s1 on abs(Products.rank - s1.rank) = x.diff 
left join Sales s2 on abs(Products.rank - s2.rank) = x.diff 
    and s2.sales > s1.sales 
    and s1.rank != s2.rank 
set Products.sales = s1.sales 
where s2.rank is null 

は、ここで完全なスクリプトは次のとおりです。

create table Products (ID int, Sales int, Rank int); 
insert into Products values 
(1,0,100), 
(2,0,105), 
(3,0,200), 
(4,0,900); 

create table Sales (ID int, Sales int, Rank int); 
insert into Sales values 
(1,2000,99), 
(2,5000,106), 
(3,8000,800), 
(4,2500,950); 

update Products 
join (select p.rank, min(abs(s.rank - p.rank)) diff 
    from Sales s 
    cross join Products p 
    group by 1) x on Products.rank = x.rank 
join Sales s1 on abs(Products.rank - s1.rank) = x.diff 
left join Sales s2 on abs(Products.rank - s2.rank) = x.diff 
    and s2.sales > s1.sales 
    and s1.rank != s2.rank 
set Products.sales = s1.sales 
where s2.rank is null; 

select * from Products; 

出力:

+------+-------+------+ 
| ID | Sales | Rank | 
+------+-------+------+ 
| 1 | 2000 | 100 | 
| 2 | 5000 | 105 | 
| 3 | 5000 | 200 | 
| 4 | 2500 | 900 | 
+------+-------+------+ 
関連する問題