sql查询合并两个表的数据并显示输出

时间:2015-04-01 15:40:27

标签: php mysql sql

以下是我的两张表。

我需要相应地加入表数据和获取结果......

FOR EX -

方案主表中,有8行具有不同的收据号。

收据输入表中,只创建了2张收据......

所以我只需要显示来自方案主表的那些余额收据哪个账簿和收据不存在在收据输入表中。

表名 - scheme_master

book_no2    receipt_no   createddate
401           10          15-03-2015
401           11          15-03-2015
401           12          15-03-2015
401           13          15-03-2015
403           25          15-03-2015
403           26          15-03-2015
403           27          15-03-2015
403           28          15-03-2015
405           35          15-03-2015
405           36          15-03-2015
405           37          15-03-2015
405           38          15-03-2015

表名 - Receipt_entry

book_no  receipt_no   
401         10           
403         26        

我只需要获得收据条目表中没有的收据。

预期输出

Book No     Balance Receipt      createddate  

401           11          15-03-2015
401           12          15-03-2015
401           13          15-03-2015

403           25          15-03-2015   
403           27          15-03-2015
403           28          15-03-2015

SQL:

 SELECT DISTINCT SM.receipt_no AS Receipt,SM.book_no2 AS book,SM.created AS printedDate,SM.city AS cityname FROM scheme_master SM
     LEFT JOIN receipt_entry RE ON RE.receipt_no = SM.receipt_no WHERE
      SM.book_no2 BETWEEN :book_no AND :book2 AND RE.receipt_no IS NULL

4 个答案:

答案 0 :(得分:1)

首先,如果您在distinctbook_no上正确加入,则不需要receipt_no。其次,where子句中的条件是将left join变为inner join,因为NULL值无法进行比较。这个条件应该放在第一个表格上,而不是第二个表格。

所以,试试这个:

SELECT SM.book_no2 AS book, SM.created AS printedDate,
       SM.receipt_no AS Receipt, RE.bookingdate AS bookingdate, RE.surveyor_name FROM scheme_master SM LEFT JOIN
     receipt_entry RE
     ON RE.book_no = SM.book_no2 AND RE.receipt_no = SM.receipt_no
WHERE SM.book_no = 401;

答案 1 :(得分:1)

SELECT SM.book_no2 AS book,SM.created AS printedDate,SM.receipt_no AS Receipt,RE.bookingdate AS bookingdate,RE.surveyor_name 
FROM scheme_master SM
INNER JOIN Receipt_entry RE
ON RE.book_no = SM.book_no2 AND RE.receipt_no = SM.receipt_no
WHERE RE.book_no = 401;

答案 2 :(得分:0)

这将是您的原始查询:

SELECT DISTINCT SM.book_no2 AS book,SM.created AS printedDate,SM.receipt_no AS Receipt,RE.bookingdate AS bookingdate,RE.surveyor_name 
FROM scheme_master SM
LEFT JOIN receipt_entry RE ON RE.book_no = SM.book_no2

您可以像这样修改它以满足您的需求:

SELECT SM.book_no2 AS book, SM.created AS printedDate,SM.receipt_no AS Receipt, RE.bookingdate AS bookingdate, RE.surveyor_name 
FROM scheme_master SM 
LEFT JOIN receipt_entry RE
ON RE.book_no = SM.book_no2 
AND RE.receipt_no = SM.receipt_no;

我们离开了两个语句,以便查询将在same row中输出具有相同book_numberreceipt_number的值,然后显示booking date和{{1有或没有数据。

编辑:

请检查以下

surveyor name

答案 3 :(得分:0)

您可以尝试以下查询:

select s.book_no2 as "Book No", s.receipt_no as "Balance Receipt", s.createddate
  from scheme s join receipt r on (s.book_no2 = r.book_no) 
  where s.receipt_no not in (select receipt_no from receipt);

可以在此处看到演示结果:SQLFiddle