MySQL - JOIN的嵌套select语句?

时间:2013-12-17 13:18:40

标签: mysql sql join

我有3个表正在使用内部联接加入。表格是:

发票,合同和计费表。

一些简化的样本数据:

//invoice

id | contract_id

1  | 123

//contract

id  | meter_id | supplier     | end_date

123 | 100      | British Gas  | 2013-12-20

456 | 100      | nPower       | 2014-03-03

//meter

id  | meter-id
1   | 100

我的目标是加入表格,但只检索最新的(MAX)end_date并获得供应商。通常情况下这不是问题,但我只有合同123加入,而不是合同456.如图所示,它们都共享相同的meter_id。

//Current query
SELECT
contract.supplier AS supplierName
FROM invoice
INNER JOIN contract ON contract.id=invoice.contract_id
INNER JOIN meter ON meter.id=contract.meter_id

我该怎么做?是通过嵌套选择还是什么?感谢

4 个答案:

答案 0 :(得分:5)

SELECT *
FROM
(
    SELECT meter_id, supplier, MAX(end_date) end_date
    FROM contract 
    GROUP BY meter_id, supplier
) a
JOIN contract c ON c.meter_id = a.meter_id AND a.end_date = c.end_date
JOIN meter m ON m.meter-id = c.meter_id
JOIN invoice i ON i.contract_id = c.id

答案 1 :(得分:3)

应该是这样的:

    SELECT contract.supplier AS supplierName
    FROM invoice
    INNER JOIN contract ON contract.id=invoice.contract_id
    INNER JOIN meter ON meter.meter_id=contract.meter_id
    order by end_date DESC 
    limit 1

答案 2 :(得分:0)

希望这是你想要的&这应该有效。

SELECT
contract.supplier AS 'supplierName'
end_date AS 'end_date'
FROM contract
INNER JOIN invoice ON contract.id=invoice.contract_id
INNER JOIN meter ON meter.id=contract.meter_id
WHERE end_date in (select MAX(end_date) from contract)

如果您希望每个供应商都是最新(MAX)end_date,只需更改子查询&按供应商添加组。

答案 3 :(得分:0)

select i.contract_id,m.meter_id,c.supplier,c.end_date
from invoice i
inner join contract c on i.contract_id=c.id
inner join meter m c.meter_id=m.meter_id