简体   繁体   English

MySQL:LEFT JOIN选择

[英]MySQL: SELECT with LEFT JOIN

how can I join two tables and make the second optional? 如何连接两个表并使第二个表可选?

SELECT t1.title,SUM(t2.seconds) AS seconds 
FROM operation t1 
  LEFT JOIN workhours t2 ON t1.id = t2.pid AND t1.status='0' 
ORDER BY t1.tstamp DESC

This query shows only one result but there is a second one withour any worktime on it. 此查询仅显示一个结果,但第二个结果中包含任何工作时间。 How can I make sure that the data from t1 will always be displayed even when there is nothing in t2? 即使t2中没有任何内容,如何确保始终显示t1中的数据?

You need to add GROUP BY t1.title : 您需要添加GROUP BY t1.title

SELECT t1.title,SUM(t2.seconds) AS seconds 
FROM operation t1 LEFT JOIN workhours t2 ON t1.id = t2.pid AND t1.status='0' 
GROUP BY t1.title
ORDER BY t1.tstamp DESC

In general, if title is not unique, you should group by unique key. 通常,如果title不是唯一的,则应按唯一键分组。

如果你需要总是得到第一个的结果与第二个结果不匹配,那么你必须使用Left Outer Join如果另一个表与第二个表没有任何匹配的结果,它将始终显示结果如果第二个匹配或不匹配,则第一个独立。

It seems that the issue may be in the "SUM(t2.seconds)" parameter on your select. 似乎问题可能出在select的“SUM(t2.seconds)”参数中。

Try adding ISNULL(SUM(t2.seconds), 0). 尝试添加ISNULL(SUM(t2.seconds),0)。

If that doesn't work, you might try a SQL IF statement or CASE and check a column on t2 for nulls. 如果这不起作用,您可以尝试SQL IF语句或CASE并检查t2上的列是否为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM