简体   繁体   中英

Selecting unique id in mysql

Below is the replicas of the tables I have created. My goal is to simply pick the unique id_num from the First Table which is not found on the Second Table.

I have tried doing the code below but somehow, I kept getting empty results

SELECT `first_table`.name FROM `first_table`
INNER JOIN `second_table`
ON `first_table`.id_num = `second_table`.id_num
WHERE `first_table`.name = `second_table`.name 

First Table:

   id_num   |  name
    301     |  Bobby
    123     |  George
    25      |  Vicky

Second Table:

   id_num   |  name
    301     |  Bobby
    435     |  George
    25      |  Vicky

My desire result I am looking for:

id_num   |  name
435     |  George

LEFT JOIN should work here.

SELECT `first_table`.name FROM `first_table`
LEFT JOIN `second_table`
ON `first_table`.id_num = `second_table`.id_num
WHERE `second_table`.id_num is NULL

See also this useful infographic

在此处输入图片说明

try this using NOT IN

select `id_num` , name from `table2` where name not in (
                                                  SELECT t1.name FROM `table1` t1
                                                  INNER JOIN `table2` t2
                                                  ON t1.id_num = t2.id_num )

DEMO HERE

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