What I am trying to do, using java, is:
- access a database
- read a record from table “Target_stats”
- if the field “threat_level” = 0, doAction1
- if the field “threat_level” > 0, get additional fields from another table “Attacker_stats” and doAction2
- read the next record
Now I have everything I need but a well thought out SQL statement that will allow me to only go through the database only once, if this does not work I suspect I will need to use two separate SQL statements and go through the database a second time. I do not have a clear understanding of case statements, so I will just provide pseudo code using an if statement.
SELECT A.1, A.2, A.3
if(A.3 > 0){
SELECT A.1, A.2, A.3, B.1, B.3
FROM A
JOIN B
ON A.1 = B.1
}
FROM A
Can anyone shed any light on my situation?
EDIT: Thankyou both for your time and effort. I understand both of your comments and I believe that I am headed more towards the right direction however, I’m still having some trouble. I didn’t know about SQLfiddle before so I have now gone ahead and made a sample DB and tried to demonstrate my purpose. Here is the link: http://sqlfiddle.com/#!3/ea108/1 What I want to do here is Select target_stats.server_id, target_stats.target, target_stats.threat_level Where interval_id=3 and if the threat_level>0 I want to retrieve attack_stats.attacker, attack_stats.sig_name Where interval_id=3. Again, thankyou for your time and effort it is very useful to me
EDIT: after some tinkering around, I figured it out. thankyou so much for your help
As @Ocelot20 said, SQL is not procedural code. It is based on set-based operations, not per row operations. One immediate consequence of this is that the
SELECTin your pseudo-example is wrong as it relies on rows in the same result set having different column lists.That said, you can get pretty close to your pseudo-code example, if you can tolerate
NULLvalues where the join is not possible.Here’s an example that (to me anyway) seems to be close to what your are driving at:
You can see it in action in this SQLFiddle, which should show you what sort of output to expect.
Note that what this is actually saying is something like this:
(This was picked for convenience. In my rather contrived example shifting the conditional column does not effect the output as can be see here).