简体   繁体   中英

MySQL SELECT Query with WHERE clause Not returning rows from two tables

I have two tables InvoicePDF and UserMaster. They are connected using a common column (CompanyID). When I try to run the below query, I am getting empty result set. Curious to know why?

By the way I wish to return all the rows of the first table matching the CompanyID in the second table where the CustomerID is 3.

SELECT A.CompanyID,
B.COMPANYID,
B.CUSTOMERID,
A.InvPDFFileName,
A.InvMonth,
A.InvYear,
A.InvoiceID 
FROM InvoicePDF A, UserMaster B 
WHERE B.CompanyID=A.CompanyID and B.CustomerID=3

use left join and apply your condition B.CustomerID=3 in ON Cluase - and always use an explicit join instead of implicit one

SELECT A.CompanyID,B.COMPANYID,
B.CUSTOMERID,A.InvPDFFileName,
A.InvMonth,A.InvYear,A.InvoiceID 
FROM InvoicePDF A left join UserMaster B on B.CompanyID=A.CompanyID and B.CustomerID=3

Your query works as expected

DROP TABLE IF EXISTS INVOICEPDF,USERMASTER;
CREATE TABLE INVOICEPDF(COMPANYID INT   , InvPDFFileName varchar(3),InvoiceID int);
create table usermaster(COMPANYID int,CUSTOMERID int);

insert into invoicepdf values
(1,'aaa',1),(2,'bbb',2),(1,'aaa',3);
insert into usermaster values
(1,3),(2,4),(3,3);



SELECT A.CompanyID,
B.COMPANYID,
B.CUSTOMERID,
A.InvPDFFileName,
#A.InvMonth,
#A.InvYear,
A.InvoiceID 
FROM InvoicePDF A, UserMaster B 
WHERE B.CompanyID=A.CompanyID and B.CustomerID=3;

+-----------+-----------+------------+----------------+-----------+
| CompanyID | COMPANYID | CUSTOMERID | InvPDFFileName | InvoiceID |
+-----------+-----------+------------+----------------+-----------+
|         1 |         1 |          3 | aaa            |         1 |
|         1 |         1 |          3 | aaa            |         3 |
+-----------+-----------+------------+----------------+-----------+
2 rows in set (0.00 sec)

Which means one or more of your where conditions is false.

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.

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