Index: lib/Mail/SpamAssassin/BayesStore/MySQL.pm
===================================================================
--- lib/Mail/SpamAssassin/BayesStore/MySQL.pm	(revision 1581888)
+++ lib/Mail/SpamAssassin/BayesStore/MySQL.pm	(working copy)
@@ -698,6 +698,11 @@
 
   my $sqlselect = "SELECT id FROM bayes_vars WHERE username = ?";
 
+  if ($self->{bayes}->{conf}->{bayes_sql_username_custom_query}) {
+      dbg("bayes: _initialize_db: Using custom query for username -> id lookup")
+      $sqlselect = $self->{bayes}->{conf}->{bayes_sql_username_custom_query}
+  }
+
   my $sthselect = $self->{_dbh}->prepare_cached($sqlselect);
 
   unless (defined($sthselect)) {
Index: lib/Mail/SpamAssassin/BayesStore/SQL.pm
===================================================================
--- lib/Mail/SpamAssassin/BayesStore/SQL.pm	(revision 1581888)
+++ lib/Mail/SpamAssassin/BayesStore/SQL.pm	(working copy)
@@ -1762,6 +1762,11 @@
 
   my $sqlselect = "SELECT id FROM bayes_vars WHERE username = ?";
 
+  if ($self->{bayes}->{conf}->{bayes_sql_username_custom_query}) {
+      dbg("bayes: _initialize_db: Using custom query for username -> id lookup")
+      $sqlselect = $self->{bayes}->{conf}->{bayes_sql_username_custom_query}
+  }
+
   my $sthselect = $self->{_dbh}->prepare_cached($sqlselect);
 
   unless (defined($sthselect)) {
Index: masses/bayes-testing/benchmark/tests/mysql/site/local.cf
===================================================================
--- masses/bayes-testing/benchmark/tests/mysql/site/local.cf	(revision 1581888)
+++ masses/bayes-testing/benchmark/tests/mysql/site/local.cf	(working copy)
@@ -10,4 +10,6 @@
 
 bayes_sql_override_username benchmark
 
+#bayes_sql_username_custom_query SELECT id FROM bayes_vars WHERE username = spam_user(?)
+
 #bayes_auto_learn 0
Index: masses/bayes-testing/benchmark/tests/pgsql/site/local.cf
===================================================================
--- masses/bayes-testing/benchmark/tests/pgsql/site/local.cf	(revision 1581888)
+++ masses/bayes-testing/benchmark/tests/pgsql/site/local.cf	(working copy)
@@ -10,4 +10,6 @@
 
 bayes_sql_override_username benchmark
 
+#bayes_sql_username_custom_query SELECT id FROM bayes_vars WHERE username = spam_user(?)
+
 #bayes_auto_learn 0
Index: sql/README.bayes
===================================================================
--- sql/README.bayes	(revision 1581888)
+++ sql/README.bayes	(working copy)
@@ -77,6 +77,13 @@
 trick sa-learn to learn data as a specific user.
 
 
+bayes_sql_username_custom_query somequery
+
+This option gives you the ability to create a custom SQL query to
+retrieve user id.  In order to work correctly your query should 
+return one value, the id.  In addition, there is one variable 
+expected which is username.
+
 Requirements
 ------------
 
