2014-11-08 78 views
0

如果问题本身没有多大意义,我很抱歉,但让我解释一下。如何在一个中显示2个不同查询的结果?

我有2个表:医药及捐赠

医学:

id_medicine 医药 量

和捐赠有:

id_donation id_medicine 量

什么我想要一个查询来显示可用药物的总量。

我有此查询:

SELECT Medicine.name AS 'Medicine', Medicamento.quantity + Donation.quantity AS Quantity 
    FROM Donation 
    INNER JOIN medicine ON donation.cod_medicine = Medicine.cod_medicine 
    ORDER BY 'Medicine' 

但只显示也有捐赠,如果药物没有一个单一的捐款则不会显示出来的药。那么,即使没有捐赠,我又怎么能得到每种药物的总量呢?谢谢!

+0

这是否适合特定的SQL:TSQL,MySQL,Oracle等? – Kennah 2014-11-08 03:34:28

+0

它是微软SQL – Hikaros 2014-11-08 03:40:54

回答

1

你可能在你的OUTER JOIN连同NVL函数(假定它是Oracle数据库):

SELECT Medicine.name AS 'Medicine', Medicamento.quantity + NVL(Donation.quantity, 0) AS Quantity 
FROM Donation 
LEFT OUTER JOIN medicine ON donation.cod_medicine = Medicine.cod_medicine 
ORDER BY 'Medicine' 

如果它是SQL Server中,与ISNULL

更换NVL的NVL或ISNULL功能服务用其他值代替空值,函数的第二个参数,这里是0.

+0

哦这个做这样的工作: '选择Medicamento.nombre_Medicamento AS 'Medicamento',Medicamento.fecha_Vencimiento, Medicamento.cantidad + Donacion_Medicamento.Cantidad AS Cantidad FROM Donacion_Medicamento INNER JOIN Medicamento ON Donacion_Medicamento.cod_Medicamento = Medicamento.cod_Medicamento ORDER BY'Medicamento'' (这是微软的SQL,但很少有研究很容易改变它)谢谢!我有一个问题,但是你碰巧知道如何合并具有相同药物名称的记录? – Hikaros 2014-11-08 03:51:02

+0

例如我从查询中得到了这个结果: [链接](http://puu.sh/cHHTw/08eefe927a.png) 我该如何合并具有相同名称“panadol”的记录并添加它们数量? – Hikaros 2014-11-08 03:53:56

+1

你可以添加一个“GROUP BY”,然后是你想要分组的字段(所以对于你所有的字段,除了'Medicamento'我猜) – Jalayn 2014-11-08 03:57:50

1

试试这个

SELECT 
    Medicine.name AS Medicine 
    , Medicine.quantity + COALESCE(Donation.quantity, 0) AS Quantity 
FROM Medicine 
    LEFT JOIN Donation ON donation.id_medicine = Medicine.id_medicine 
ORDER BY Medicine 
相关问题