我有这个mysql声明:
SELECT ca.*, MAX(ca.id), v.*,a.submit_dt from callback_holding ca
inner join valuations v on v.Ref = ca.ref
inner join answer a on a.title = ca.ref
where v.Consultant = '$user' and ca.isholding = 2
GROUP BY ca.ref DESC order by ca.reccomendeddate asc
但问题是如果“回答”中没有条目,则它不会显示在列表中。如果“回答”表中没有任何内容,那么恢复所有内容的正确方法是什么,只是“空”?
由于
答案 0 :(得分:0)
您的查询有几个问题。首先,您要按ref
表中的callback_holding
列进行分组,但不仅要从此表中选择非聚合列,还要从其他表中选择非聚合列。要解决此问题,您应该进行聚合以在子查询中的callback_holding
中查找最大ID,然后将其连接到其他表。
接下来,你提到如果没有找到答案,你就不会找回任何记录。这是INNER JOIN
的性质,但如果您将联接切换为answer
以使用LEFT JOIN
,则查询中不会丢失任何记录。请注意,如果答案表中的此列为COALESCE(a.submit_dt, 'NA')
,我会使用NA
来显示NULL
。如果此列为datetime
,那么您应该使用合适的默认值,例如NOW()
。
SELECT ca.*,
v.*,
COALESCE(a.submit_dt, 'NA') AS submit_dt, -- display 'NA' if no answer
t.max_id
FROM callback_holding ca
INNER JOIN
(
SELECT ref, MAX(id) AS max_id
FROM callback_holding
GROUP BY ref
) t
ON t.ref = ca.ref AND
t.max_id = ca.id
INNER JOIN valuations v
ON v.Ref = ca.ref
LEFT JOIN answer a
ON a.title = ca.ref
WHERE v.Consultant = '$user' AND
ca.isholding = 2
ORDER BY ca.reccomendeddate
答案 1 :(得分:0)
尝试:
SELECT ca.*, MAX(ca.id), v.*,a.submit_dt from callback_holding ca
INNER join valuations v on v.Ref = ca.ref
LEFT join answer a on a.title = ca.ref
WHERE v.Consultant = '$user' and ca.isholding = 2
GROUP BY ca.ref DESC order by ca.reccomendeddate asc