简体   繁体   中英

MySql select from two tables if row doesn't exist in the second

I have two tables table 1 and table 2 table 2 contain the id of table 1

I want to show all field of table 1 with 2 column from table 2 who have the id of table 1 and if the table 2 don't have a record for table 1 (don't have id of table 1) the result will be the content of table 1 with the 2 columns will be empty this the query i use

select *
from tbl_marketing
right join tbl_phonecall on tbl_marketing.db_maid=tbl_phonecall.db_mid 
where tbl_marketing.db_status!='Deal Done' and tbl_marketing.db_status!='Refused' and tbl_marketing.db_status!='Not Interested' order by tbl_marketing.db_date desc,tbl_phonecall.db_nextdate desc

But this query don't give me the results i want

if i don't have information on table 2 for a row in table 1 this row will not be appear on my result

How can i solve this problem ?!

2017-02-10 12:46:01 vv  ddd  Answered 2017-01-01 00:00:00   2017-02-24 00:00:00

this is data from first table :

2017-02-10 12:46:01 vv  ddd  Answered

this is data from second table:

2017-01-01 00:00:00 2017-02-24 00:00:00

if second table don't have data for the frist table the data in the first don't appear if not it's appear like above i want if in the second table i don't have data for the first table the result be like that

2017-02-10 12:46:01 vv  ddd  Answered

that last 2 columns be empty tbl_marketing 在此处输入图片说明

tbl_phonecall 在此处输入图片说明

the result will be all the field in tbl_marketing without repetition if in tbl_phonecall have two rows or more and if i don't have rows in tbl_phonecall for a field in tbl_marketing it will showed with empty value for db_due and db_nextdate

Use the left join (I am assuming table 1 is tbl_marketing)..

SELECT 
      tbl_marketing.* , tbl_phonecall.db_due, tbl_phonecall.db_nextdate
    FROM
      tbl_marketing 
      LEFT JOIN (SELECT db_mid, max(db_due) db_due, max(db_nextdate) db_nextdate FROM tbl_phonecall group by db_mid) tbl_phonecall
        ON tbl_marketing.db_maid = tbl_phonecall.db_mid 
    WHERE tbl_marketing.db_status != 'Deal Done'
      AND tbl_marketing.db_status != 'Refused'
      AND tbl_marketing.db_status != 'Not Interested' 
    ORDER BY tbl_marketing.db_date DESC,
      tbl_phonecall.db_nextdate DESC;

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