I have the following 3 tables
Table1
ID | NAME
-----------
1 | X
2 | Y
3 | Z
Table2
ID | NAME
-----------
1 | A
2 | B
3 | C
Table3
ID | P (Boolean field) | Other cols
1 | True ...
2 | True....
1 | False
Now I need a query on table3 that has to do the following:
To display the name field of table1 and table2. But my problem is that
if field P on table3 is true I want it to display the name of table2’s field where table2.id = table3.id but if it is false I need it to read the name of table1’s name field where table1.id = table3.id.
The program which will display the results is a desktop application and i could do it with some procedure or something to display them, but would be nicer if I had a SQL query to do this for me.
This:
, or this:
In systems capable of doing
HASH JOIN(that isOracle,SQL Server,PostgreSQL, but notMySQL), the second one is better if the boolean values are distributed evenly, i. e. there are lots of bothTRUE‘s andFALSE‘s, and iftable3is quite large.The first one is better if there is a skew in distribution, if there are much fewer rows in
table3then intable1ortable2, or if you are usingMySQL.Update:
If the majority of fields are false, the following query will probably be the best:
Subquery here will only be used as a fallback, and will be executed only for the rare
TRUEvalues.Update 2:
I can’t check it on Firebird, but on most systems the
ORDER BYsyntax as in query above will work. If it does not, wrap the query into an inline view:, though it may hamper performance (at least in
MySQLit does).