我有一个sql查询,它返回一个住宅单元列表,以及一个应该获得该单元最后输入账单的子查询。
但是,当我将LIMIT 1添加到子查询时,不返回任何条目条目?如果我把它遗漏,我会得到重复的单位行,具体取决于单位的账单数量。
select * from unit u
left join (select id as billId, unit_id, added_on, end_reading, bill_type from bills
order by id desc) b ON unit_id = u.id
where community_Id = 1
and unit_section = 7
and unit_floor in (1,2,3,4,5)
order by unit_floor, display_order asc;
任何人都知道如何将子查询结果限制为1个账单?
此致
鲍勃
答案 0 :(得分:0)
使用复制结果的联接时,请添加group by
语句。它是简单选择
distinct
的替代品
select * from unit u
left join (select id as billId, unit_id, added_on, end_reading, bill_type from bills
order by id desc) b ON unit_id = u.id
where community_Id = 1
and unit_section = 7
and unit_floor in (1,2,3,4,5)
group by u.id
order by unit_floor, display_order asc;
答案 1 :(得分:0)
认为您需要一个子查询来从bill表中获取每个unit_id的第一个(最低)id。然后使用它来连接单位和账单表,从最低ID的账单中获取其他匹配的列
SELECT u.*, bills.*
FROM unit u
LEFT OUTER JOIN
(
SELECT unit_id, MIN(id) AS min_id
FROM bills
GROUP BY unit_id
) b ON b.unit_id = u.id
LEFT OUTER JOIN bills
ON b.unit_id = bills.unit_id
AND b.min_id = bills.id
WHERE u.community_Id = 1
AND u.unit_section = 7
AND u.unit_floor in (1,2,3,4,5)
ORDER BY u.unit_floor, u.display_order asc;