How to Get A Count From Another Table In SQL?

我的梦境 提交于 2019-12-24 04:02:21

问题


I have the following tables on SQL:

Mensajes

IdMensaje (int) PK NOT NULL
IdCliente (int)
CorreoCliente (varchar(100))
CorreosAdicionales (varchar(MAX))
Tema (varchar(100))
Mensaje (varchar(MAX))
Fecha (date)
Hora (time(5))

Archivos

IdArchivo (int) PK NOT NULL
IdMensaje (int)
Nombre (varchar(200))

Foreign Key Mensajes.IdMensaje ON Archivos.IdMensaje

If you are wondering what Mensajes.IdCliente is, yes, it has a foreign key with another table but that's another story

First an intro... I'm making a program in which you send an email... When you send an email, I'll insert all data on Mensajes, and if you attached Files on the message, it will also insert on Archivos for each file (obviously Archivos.IdMensaje equals to the Mensajes.IdMensaje which was inserted before that)

So here's my question: I want to make a query where I get All data from Mensajes, but also add another column where it will display how many files were attached to that message... I managed to use a query in which I did get that data (well, sort of)

SELECT Mensajes.IdMensaje, COUNT(Archivos.IdArchivo) AS Expr1
FROM Mensajes INNER JOIN Archivos ON Mensajes.IdMensaje = Archivos.IdMensaje
GROUP BY Mensajes.IdMensaje

However it only displays the messages that had files attached to it, not the ones with a result of 0, I want to display those messages as well... How do I do that?

Hope you can help me Thanks


回答1:


Change your INNER JOIN to a LEFT OUTER JOIN; this will select all records from Mensajes even if they don't have a related record in Archivos.



来源:https://stackoverflow.com/questions/11939989/how-to-get-a-count-from-another-table-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!