mysql - How to write SQL Query for this condition -


i have 2 tables 1 "batch" , 1 "batchdetails". batch have columns batchid,batchname, , techid. batchdetails have columns batchdetailsid,batchid , subtechid.

batchdetails table connected batch table "batchid". there 1 many relationship between "batch" , "batchdetail" table. 1 batch have multiple entries in batchdetails table.

now want select batchname batch techid=1 , corresponding batchname, batchdetails table have subtechid=1 , subtechid=2.

there's several approaches returning specified result.

assuming specification return only rows batch have @ least 2 associated rows in batchdetails, , @ least 1 of associated rows subtechid=1 , @ least 1 subtechid=2

for mysql:

 select b.batchname     batch b    join batchdetail d1      on d1.batchid = b.batchid     , d1.subtechid = 1    join batchdetail d2      on d2.batchid = b.batchid     , d2.subtechid = 2   b.techid = 1   group b.batchid   order b.batchname 

it's possible equivalent result using exists predicates:

 select b.batchname    batch b   b.techid = 1     , exists ( select 1                    batchdetail d1                   d1.batchid = b.batchid                     , d1.subtechid = 1                 )     , exists ( select 1                    batchdetail d2                   d2.batchid = b.batchid                     , d2.subtechid = 2                 )   order b.batchname 

or, getting count of distinct values of subtechid , comparing constant

 select b.batchname    batch b    join batchdetail d      on d.batchid = b.batchid     , d.subtechid in (1,2)   b.techid = 1    group b.batchid   having count(distinct d.subtechid) = 2    order b.batchname 

there several other query patterns...


Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -