sql查询连接三个表并选择数据(如果存在)

时间:2015-04-07 12:56:50

标签: php mysql

以下是我的三张数据表..

我需要从schememaster中选择book_no2,receipt_no,createddate并加入图书发行和图书归还表。

现在需要检查一下,如果发行了书籍,则会显示针对本书的内容。

AND如果书籍被退回,则需要显示返回日期对照那些书和收据号..

表名schemeMaster

book_no2    receipt_no      createddate

70          100           2015-02-20
70          101           2015-02-20
70          102           2015-02-20
70          103           2015-02-20
70          104           2015-02-20
70          105           2015-02-20
70          106           2015-02-20

表名bookissue

bookno         issuedate
 70            04-03-2015    
 70            05-03-2015
 70            06-03-2015

表名bookreturn

bookno   usedreceipt         returndate
 70          100             04-03-2015
 70          101             04-03-2015
 70          102             05-03-2015
 70          103             07-03-2015

预期输出

  bookno receiptno   createdddate   IssueDate     ReturnDate    
  70      100         2015-02-20    04-03-2015    04-03-2015     
  70      101         2015-02-20    ----------    04-03-2015     
  70      102         2015-02-20    05-03-2015    05-03-2015     
  70      103         2015-02-20    06-03-2015    07-03-2015     
  70      104         2015-02-20    ---------     ---------
  70      105         2015-02-20    ---------     ---------      
  70      106         2015-02-20    ---------     ---------      

我尝试下面的查询,获取数据但不正确,因为我想..

我的查询显示问题并返回所有行....在那些收据中也没有在图书归还表中。

FOR EX - 在上面的例子中 - 有3个数据表...

我需要从方案主表中选择所有数据并显示已发布和返回,如果可用,则在此列上显示空白...

SELECT DISTINCT SM.book_no2 As Book, 
SM.created AS Printeddate, 
BI.issue_date AS issuedate, 
BR.return_date AS returndate,
BR.used_receipt AS totalreceipt 
FROM scheme_master SM 
LEFT JOIN book_issue BI 
ON (SM.book_no2 = BI.book_no ) 
LEFT JOIN book_return BR 
ON ( BR.book = BI.book_no ) 
WHERE SM.city = 'nagpur' 
AND SM.book_no2 BETWEEN 70 AND 70

1 个答案:

答案 0 :(得分:0)

select s.book_no2, s.reciept_no, s.createddate, b.issuedate, br.returndate
from schememaster as s
left join bookissue as b on b.bookno = s.book_no2
left join bookreturn as br on br.bookno = s.book_no2

这会产生类似输出的结果,但不确定它是否符合您的要求。