I'm developing a C# application for a local business. I want to select data from 3 tables of a SQL Server 2014 database, namely companyinfo
, invmain
, invtran
.
Companyinfo
stores the name of business, invmain
has sales invoice number and date info while invtran
has Invoice Transaction.
I'm using a SELECT statement like this:
SELECT
companyinfo.name,
invmain.invno, invmain.date, invtrans.itemid, invtrans.unitprice
FROM
companyinfo, invmain, invtrans
WHERE
companyinfo.Id = 1
AND invmain.invno = 13
AND invtrans.invnumber = 13
But this returns null if one of table has no data. Is there any other effective way to do that?
Use the proper ANSI/SQL JOIN syntax like this:
SELECT
ci.name,
invmain.invno, invmain.date,
invtrans.itemid, invtrans.unitprice
FROM
companyinfo ci,
INNER JOIN
invmain m ON ci.companyId = m.companyId
INNER JOIN
invtrans it ON it.invo = m.invno
WHERE
companyinfo.Id = 1
and you need to define JOIN conditions between the tables to establish the "links". I've chosen INNER JOIN
which returns only rows that exist in both tables involved, based on the matching condition defined after the ON
keyword.
If you want to select rows from companyinfo
that don't have any corresponding invoices, you could also use LEFT OUTER JOIN
instead of the INNER JOIN
to get back data from companyinfo
for companies without any invoices
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.