简体   繁体   中英

MySQL left outer join query

I have two tables,

first table structure (data) :

-id
-name
-title
-mail
-source_id

and second table ( mail ) :

-id
-record_id
-mail
-date

there may be some duplicate records in data table and some records with empty mail field. im sending emails to these clients and i want to save whos email has been sent with time in mail table. and i want to exclude records which their emails has been already sent

i use this query :

SELECT * FROM `data`
LEFT OUTER JOIN `mail`
ON `data`.`source_id` != `mail`.`record_id`
WHERE `data`.`mail` != ''
ORDER BY `data`.`id` ASC LIMIT 1

also i tried :

SELECT * FROM `data`
LEFT OUTER JOIN `mail`
USING(`mail`)
WHERE `data`.`mail` != ''
ORDER BY `data`.`id` ASC LIMIT 1

but it still shows duplicate records and dont exclude records from mail table

any ideas ? or better solution ? btw i cant alter first table and add a new field for checking sent emails

thanks in advance

try this

let's change != to IS NOT NULL (I also think you should use <> instead of != )

SELECT * FROM `data`
LEFT OUTER JOIN `mail`
ON `data`.`source_id` != `mail`.`record_id`
WHERE `data`.`mail` IS NOT NULL
ORDER BY `data`.`id` ASC LIMIT 1

UPDATE: let's try DISTINCT

SELECT (DISTINCT data.email) FROM `data`
LEFT OUTER JOIN `mail`
ON `data`.`source_id` != `mail`.`record_id`
WHERE `data`.`mail` IS NOT NULL
ORDER BY `data`.`id` ASC LIMIT 1

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