我正在使用子查询,我需要在customers_notes
中显示LEFT JOIN
表格中的最新音符。
我试过的查询是返回错误。
我在下面做错了什么?
SELECT c.*, n.datesubmitted
FROM `customers` c
LEFT JOIN (SELECT datesubmitted FROM `customers_notes`
ORDER BY datesubmitted DESC LIMIT 1) AS n
ON (c.customerid = n.customerid)
我得到的错误是:#1054 - 'on clause'中的未知列'n.customerid'
答案 0 :(得分:2)
首先,您错过customerid
作为您在子查询中选择的字段 - 这就是您收到错误的原因。
其次,即使你添加了它,你也不会得到你想要的结果。
我认为您有一个客户,一个客户可以附加多个注释,并且您希望获取客户详细信息以及他最近的注释的所有详细信息。
解决此类问题的一般方法是:
在子查询中查找max()
日期,如下所示:
select customerid, max(datesubmitted)
from customer_notes
group by customerid
然后在外部查询中加入这些结果
select c.*, n.*
from customers c
left join customer_notes n
on c.customer_id = n.customer_id
left join (
select customerid, max(datesubmitted)
from customer_notes
group by customerid ) nn
on n.datesubmitted = nn.datesubmitted
答案 1 :(得分:1)
要在n.customerid
条款中使用ON
,您必须首先SELECT
:
SELECT c.*, n.datesubmitted
FROM `customers` c
LEFT JOIN (SELECT datesubmitted, customerid FROM `customers_notes`
ORDER BY datesubmitted DESC LIMIT 1) AS n
ON (c.customerid = n.customerid)
答案 2 :(得分:-1)
您缺少要加入的必填列。 在左连接查询列名称中缺少customerid。
请参阅以下查询
SELECT c.*, n.datesubmitted
FROM `customers` c
LEFT JOIN (SELECT customerid,datesubmitted FROM `customers_notes`
ORDER BY datesubmitted DESC LIMIT 1) AS n
ON (c.customerid = n.customerid)