您好我对左连接有疑问。我有两张桌子" Customer"," Meeting"常见栏目是" mkod"。
客户表有" mkod"和" customername" colums 会议桌有" mkod","详情"和#34; meetdate"
我希望看到客户的所有记录和"详细信息" mkod上的列和会议表中的最后一次会议日期。
但是我看不到会议的所有记录。
我的代码就是这样,
select c.mkod,m.details
from customer c
left join meeting m on c.mkod=m.mkod
where m.details=
(select top 1 details
from meeting
where c.mkod=meeting.mkod
order by meetingdate desc)
order by c.mkod
谢谢
答案 0 :(得分:2)
试试这个:
<强>的MySQL 强>
SELECT c.mkod, IFNULL(m.details, '') AS details
FROM customer c
LEFT JOIN (SELECT m.mkod, m.details
FROM meeting m
INNER JOIN (SELECT m.mkod, MAX(m.meetingdate) meetingdate
FROM meeting m
GROUP BY m.mkod
) a ON m.mkod = a.mkod AND m.meetingdate = a.meetingdate
) m ON c.mkod=m.mkod;
SQL Server
SELECT c.mkod, ISNULL(m.details, '') AS details
FROM customer c
LEFT JOIN (SELECT m.mkod, m.details
FROM meeting m
INNER JOIN (SELECT m.mkod, MAX(m.meetingdate) meetingdate
FROM meeting m
GROUP BY m.mkod
) a ON m.mkod = a.mkod AND m.meetingdate = a.meetingdate
) m ON c.mkod=m.mkod;
答案 1 :(得分:0)
这是您的查询:
select c.mkod, m.details
from customer c left join
meeting m
on c.mkod=m.mkod
where m.details=(select top 1 details from meeting where c.mkod=meeting.mkod order by meetingdate desc)
order by c.mkod;
where
子句在left outer join
的第二个表上有一个条件。这意味着当列值为NULL
时,条件不会返回true - 将left outer join
转换为inner join
。您可以通过将条件移动到on
子句来解决此问题:
select c.mkod, m.details
from customer c left join
meeting m
on c.mkod = m.mkod and
m.details = (select top 1 m2.details from meeting m2 where c.mkod = m2.mkod order by m2.meetingdate desc)
order by c.mkod;
此外,如果您想要最新的,那么条件不应该是meetingdate
而不是details
吗?
select c.mkod, m.details
from customer c left join
meeting m
on c.mkod = m.mkod and
m.meetingdate = (select max(m2.meetingdate) from meeting m2 where c.mkod = m2.mkod)
order by c.mkod;