ตรวจสอบว่ามีหลายรายการหรือไม่

ฉันมีตารางที่ผู้ใช้มีลักษณะดังนี้:

ID    COMPANY_ID    FIRST_NAME
1     1             John
2     1             Mary
3     2             Ivan
4     1             Arnold
5     3             Sam

ฉันต้องการแบบสอบถาม SQL ที่อาจตรวจสอบว่ามีคู่สำหรับ user_id, company_id ของบริษัทหนึ่งและส่งกลับ [[id, true], [id, false]

หมายความว่าฉันต้องการถามว่ามีผู้ใช้ [1, 4, 7, 17] ของบริษัท 2 อยู่และได้รับ [[1, true], [4, true], [7, false], [17, true]] หรือไม่

คงจะดีมากหากคุณแนะนำวิธีการทำสิ่งนี้กับ sqlalchemy Core


person Anton Trishenkov    schedule 17.05.2017    source แหล่งที่มา
comment
sql หรือ sqlalchemy.. เลือกอย่างใดอย่างหนึ่ง   -  person Vamsi Prabhala    schedule 17.05.2017
comment
แท็กคำถามของคุณด้วยฐานข้อมูลที่คุณใช้   -  person Gordon Linoff    schedule 17.05.2017
comment
ฉันไม่เข้าใจคำถาม คุณช่วยเรียบเรียงใหม่ได้ไหม   -  person Mike Tung    schedule 17.05.2017


คำตอบ (1)


ใน SQL คุณจะใช้ left join สมมติว่า Users ไม่ซ้ำกัน คุณจะดำเนินการดังนี้:

select t.id, (case when u.id is null then 0 else 1 end) as flag
from (select 1 as id union all
      select 4 union all
      select 7 union all
      select 17
     ) t left join
     users u
     on u.id = t.id and u.company = 2;
person Gordon Linoff    schedule 17.05.2017
comment
คุณสามารถใช้นิพจน์ VALUES ในการเข้าร่วม ดังนั้น from (values(1),(4),(7),(17)) t(id) left join ... ควรใช้งานได้เช่นกัน แท็ก PostgreSQL อาจเป็นแท็กใหม่ - person mu is too short; 17.05.2017
comment
@muistooshort . . . อย่างแน่นอน. แท็ก Postgres ไม่ได้อยู่ในคำถามเมื่อฉันตอบ - person Gordon Linoff; 17.05.2017