mysql - Conditional Where clause in sql -
select cola, colb car car.id in (select id make) , car.id in (select id model);
the above query works file is, there case make table has not been popluated anything. empty table. there way make join not take place on table?
basically, if table has 1 or more rows, apply condition. otherwise, ignore , dont limit it.
is there way achieve same result on left join?
edit
result algorithm:
- select stuff original table car.
- take away not in table make if make has content
- take away not in table model if model has content....
- take away in table model2 if model2 has content....
thisnk of model2 table of things dont want, , model , make tables of things want.
select cola, colb car ((select count(*) make) = 0) or id in (select id make)) , id in (select id model)
with left join:
select distinct cola, colb car join (select count(*) c make) mcount left join make on car.id = make.id join model on car.id = model.id mcount.c = 0 or make.id not null
using or
can prevent use of indexes, may better use union:
select distinct cola, colb car join make on car.id = make.id join model on car.id = model.id union select distinct cola, colb car join (select count(*) c make) make join model on car.id = model.id make.c = 0
extending left join
version both tables straightforward:
select distinct cola, colb car join (select count(*) c make) makecount left join make on car.id = make.id join (select count(*) c model) modelcount left join model on car.id = model.id (makecount.c = 0 or make.id not null) , (modelcount.c = 0 or model.id not null)
if there other tables join with, can keep repeating pattern.
doing union query harder, because need subquery each combination of join tables can empty: 1 subquery both make
, model
having rows, 1 make
, 1 model
, , 1 both being empty. if there 3 tables being joined with, expand 8 subqueries (i.e. there 2n subqueries). maybe can come way better, can't think of off top of head.
Comments
Post a Comment