I'm new to databases and SQL and trying to solve this problem since 3 days. I have a Java application which queries a SQLite database with JDBC. This works very fine so far. But I cannot figure out the SQL query I need to retrieve the desired rows. The table looks like this:
rowid | application | dstIP | dstPort | value_to_return
| | | |
0 | NULL | NULL | NULL | 26
1 | NULL | NULL | 80 | 1
2 | NULL | 192.168.178.31 | NULL | 2
3 | NULL | 192.168.178.31 | 80 | 3
4 | firefox | NULL | NULL | 4
5 | firefox | NULL | 80 | 5
6 | firefox | 192.168.178.31 | NULL | 6
7 | firefox | 192.168.178.31 | 80 | 7
My goal is to get the row where most comlumns match and if no column matches row 0 shall be selected. Here some examples:
input -> row
firefox 192.168.178.31 80 -> 7
chrome 192.168.178.31 81 -> 2
chrome 192.168.178.30 82 -> 0
someapp 192.168.178.29 80 -> 1
My best guess so far is this query
SELECT * FROM table WHERE (application IS ? OR application IS NULL)
AND (dstIP IS ? OR dstIP IS NULL)
AND (dstPort IS ? OR dstPort IS NULL)
ORDER BY application;
The ?s are replaced with the corresponding input values. This query returns row 0 in case of no match. But in case of several matches it returns several rows of course.
I could select the row I need in the Java application, but I want the database to this work for me.
I could change the database if a stored procedure would be the better choice for this problem, because SQLite does not support that.
I hope I described the problem precise enough. Any help will be appreciated.