开发者

MYSQL how to ignore a table in a 3 table query if it doesnt satisfy the statement

I am trying to have information displayed for this query:

SELECT o.sub_number,o.unique_id,o.period_from,o.period_to,o.total_amt,
       i.paid_amt,i.dated,i.payment,i.paid_by,i.entered_date,i.paid_for_unique,
       j.cheque_num,j.drawn_on,j.dated AS cheque_dated 
  FROM paid_details o, payment_details i,cheque j 
  WHERE o.unique_id=i.unique_id 
    AND o.unique_id=j.unique_id 
    AND o.sub_number IN (
        SELECT sub_number 
    开发者_如何学Python      FROM paid_details 
          WHERE unique_id LIKE '%1271437707%'
    );

it flops. Well the problem is sometimes the cheque might not have any information in it. So how do i get MYSQL to ignore that table and still continue displaying the rest of the information?

thanks!

Update

I tried:

SELECT t1.sub_number,t2.dated,t3.cheque_num 
  FROM paid_details AS t1 
  INNER JOIN payment_details AS t2 
    ON t1.unique_id=t2.unique_id 
  INNER JOIN cheque AS t3 
    ON t1.unique_id=t2.unique_id 
  WHERE t1.unique_id IN (
      SELECT unique_id 
      FROM paid_details 
      WHERE sub_number='6526'
  ); 

but it results in the empty set. If I remove the details on CHEQUE, then it gives me results.


You're looking for what's called a "Left Join":

SELECT o.sub_number,o.unique_id,o.period_from,o.period_to,o.total_amt,i.paid_amt,i.dated,i.payment,i.paid_by,i.entered_date,i.paid_for_unique,j.cheque_num,j.drawn_on,j.dated AS cheque_dated 
FROM paid_details o
    LEFT JOIN payment_details i ON o.unique_id=i.unique_id
    LEFT JOIN cheque j ON j.unique_id=o.unique_id
WHERE o.sub_number IN (SELECT sub_number FROM paid_details WHERE unique_id LIKE '%1271437707%');

I left-joined both tables, you may want to do "inner join" on payment_details if you need to have rows from both.


You should look at using Inner Joins and Left Joins instead of comma joins. You can get what you need with a left join.

Here's some more info on different joins you can do:

http://dev.mysql.com/doc/refman/5.0/en/join.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜