我有两张桌子:
mysql> desc vat_rates; +-------------+---------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------------+---------------+------+-----+---------+-------+ | rate_id | varchar(5) | NO | PRI | NULL | | | name | varchar(255) | NO | | NULL | | | type | enum('O','I') | NO | | NULL | | | default | tinyint(1) | YES | | 0 | | +-------------+---------------+------+-----+---------+-------+ 6 rows in set (0.00 sec) mysql> desc vat_rates_details; +-------------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------------+-------------+------+-----+---------+-------+ | rate_id | varchar(10) | NO | | NULL | | | effect_date | date | NO | | NULL | | | rate | float | NO | | NULL | | +-------------+-------------+------+-----+---------+-------+ 3 rows in set (0.00 sec)
我需要一个查询给我vat_rates.name,vat_rates.rate_id,vat_rates_details.rate在哪里,effect_date是MAX()但是< =而不是now()。
简化,我需要选择所有vat_rates,其中rate字段是基于effect_date的最后日期,但未来不会。
数据示例:
vat_rates:
rate_id ='L9'
name ='MyVatName'
type ='O'
默认= 1
vat_rates_details (第1行):
rate_id ='L9'
effect_date ='2000-01-01'
rate = 20
vat_rates_details (第2行):
rate_id ='L9'
effect_date ='2010-06-01'
rate = 19
vat_rates_details (第3行):
rate_id ='L9'
effect_date ='2010-07-01'
rate = 21
预期结果:
+-------------+-------------+------+ | rate_id | name | rate | +-------------+-------------+------+ | L9 | MyVatName | 19 | +-------------+-------------+------+
感谢您的时间:)
编辑:预期费率为19而非20. Tks Justin。
答案 0 :(得分:1)
select rd.rate_id, r.name, rd.rate
from (
select rate_id, max(effect_date) as MaxEffectDate
from vat_rates_details
where effect_date < now()
group by rate_id
) rdm
inner join vat_rates_details rd on rdm.rate_id = rd.rate_id and rdm.MaxEffectDate = rd.effect_date
inner join vat_rates r on rd.rate_id = r.rate_id
答案 1 :(得分:0)
其他可能的方法:
SELECT
VR.name,
VR.rate_id,
VRD1.rate
FROM
Vat_Rates VR
INNER JOIN Vat_Rate_Details VRD1 ON
VRD1.rate_id = VR.rate_id AND
VRD1.effect_date < NOW() -- Is this the correct syntax for mySQL?
LEFT OUTER JOIN Vat_Rate_Details VRD2 ON
VRD2.rate_id = VR.rate_id AND
VRD2.effect_date < NOW() AND
VRD2.effect_date > VRD1.effect_date
SELECT
VR.name,
VR.rate_id,
VRD1.rate
FROM
Vat_Rates VR
INNER JOIN Vat_Rate_Details VRD1 ON
VRD1.rate_id = VR.rate_id AND
VRD1.effect_date < NOW()
WHERE NOT EXISTS
(
SELECT *
FROM Vat_Rate_Details VRD2
WHERE
VRD2.rate_id = VR.rate_id AND
VRD2.effect_date < NOW() AND
VRD2.effect_date > VRD1.effect_date
)