Verify if ID exists in another mysql table

0

I want to know how to identify if the id of a Table A exists in a Table B. I have the following structure:

Table A

Table B

Within TABLE A there exists the id which may or may not exist in TABLE B.

The idea is to suddenly return an indicator / flag if an id exists or not in table B.

I really have no idea how to help or link, thank you!

    
asked by Diego Avila 07.06.2018 в 01:42
source

3 answers

0

I will put the answer if someone serves as a reference:

Assuming the following tables:

Table A
------------------
id | name |
 1 | beer |
 2 | wine |
------------------
table B
-----------------
id | id_table_a
1  | 1

and my expected result would like something like this:

-------------------------------
id | name | id_table_a | flag |
 1 | beer | 1          | 1    |
 2 | wine | Null       | 0    |
-------------------------------

the answer would be the following:

select a.*, b.id_table_a, case when b.id_table_a is null then 0 else 1 end as flag 
from tablea a
left join tableb b on a.id = b.id_table_a
    
answered by 21.06.2018 / 22:05
source
1

If what you want to do is make a query to validate if the id xx of table A is in table B you can do

SELECT id FROM A WHERE id in (SELECT id FROM B) WHERE id = xx
    
answered by 07.06.2018 в 03:02
-1

If you want to flagear the elements of a table that are in the other you can do this.

Update tabla_a , tabla_b  set tabla_a.flag=1 where tabla_a.id=tabla_b.id

This query is going to put a 1 in the flag field of table a. You have to create the flag field or choose the one you want. The other one to take into account is that the comparison table first has the largest number of records and then the smallest one.

I hope it serves you.

    
answered by 07.06.2018 в 05:00