I quickly prototyped the SQL query, and instead of doing it right, I just decided to break through it with the put-string, all the while thinking that it would be very slow, but this is not because I was just testing the query. To my surprise, Java says that this code takes 0 ms? Doesn't it take longer with help +, and not StringBuilderor similar?
long t = System.currentTimeMillis();
String load = "";
for (String s : loadFields)
load += s + ", ";
String sql = "SELECT ";
sql += load + "sum(relevance) AS 'score' " +
"FROM ( ";
for (int i = 0; i < searchFields.length; i++) {
sql += "SELECT ";
sql += load;
sql += rels[i] + " AS relevance FROM articles WHERE " +
searchFields[i];
sql += " LIKE '%" + terms[0] + "%' ";
for (int z = 1; z < terms.length; z++)
sql += "AND " + searchFields[i] + " LIKE '%" + terms[z] + "%' ";
if (i != searchFields.length - 1) sql += " UNION ALL ";
}
sql += ") results GROUP BY " + load.substring(0, load.length() - 2) + " ";
sql += "ORDER BY score desc, date desc";
System.out.println("Build Time: " + (System.currentTimeMillis() - t) + " ms");
Yes, this is very ugly, but it is not about iterpret SQL, but about telling me why it is so fast.
Build Time: 0 ms
Edit: I ran the test 10,000 times with 20 terms and it took about 10 seconds, about 1/10 millisecond. Now that I think about it, itβs pretty obvious that itβs not much to calculate unless I start getting really long strings.