简体   繁体   中英

Select all elements from a table, and check if they match to another table

I have two tables, and I want to take all entities from the first table, then, check if they can be related to a specific entity from another table. If they can be related the database returns 1 (or true), else it returns NULL (or false).

爱

I tried some things with LEFT JOIN but none of them work. I think the solution is simple but I can't figure it out...

Context : In my application I make two requests, the first one take all entities from oneTable, the second one take all idOT from anotherTable where idAT is equal to 2, THEN, I make a loop where I save all entities from the first request and in this loop I make another loop where I check if the current element is present on the second request. I thought they this solution was to heavy (two requests and imbricated loops) so I tried to do it directly in one request.

Thank you for your help guys ! I hope it won't make you lose your time...

Edit : @Strawberry gave me the answer in the comments, I was doing

SELECT * FROM oneTable LEFT JOIN anotherTable ON oneTable.idOT = anotherTable.idOT **WHERE** anotherTable.idAT = 2

instead of

SELECT * FROM oneTable LEFT JOIN anotherTable ON oneTable.idOT = anotherTable.idOT **AND** anotherTable.idAT = 2 

It's as simple as that... Thank you again guys.

Thank to the comments of the question the correct request is :

SELECT * FROM oneTable
LEFT JOIN anotherTable ON oneTable.idOT = anotherTable.idOT
AND anotherTable.idAT = 2;

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