如何在SQL中从另一个表获取计数? [英] How to Get A Count From Another Table In SQL?

查看:203
本文介绍了如何在SQL中从另一个表获取计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在SQL上有以下表格:

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))

外键Mensajes.IdMensaje ON Archivos.IdMensaje

Foreign Key Mensajes.IdMensaje ON Archivos.IdMensaje

如果你想知道Mensajes.IdCliente是什么,是的,它有一个外键与另一个表,但这是另一个故事

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

首先介绍...我正在制作一个程序,在其中发送电子邮件...当您发送电子邮件,我将插入所有数据在Mensajes,如果您附加文件的消息,它也将插入(显然Archivos.IdMensaje等于之前插入的Mensajes.IdMensaje)

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)

这里是我的问题:
我想创建一个查询,我获得所有的数据从Mensajes,但也添加另一个列,它将显示有多少文件附加到该消息...
我设法使用一个查询,其中我得到的数据(好,类别)

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

具有附加文件的消息,而不是结果为0的消息,我想显示这些消息...
我如何做?

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

推荐答案

更改 INNER JOIN LEFT OUTER JOIN ;即使他们在 Archivos 中没有相关记录,也将选择 Mensajes 中的所有记录。

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.

这篇关于如何在SQL中从另一个表获取计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆