Database query to check if current user has created a node reference? I have a content type B with a node reference field (from url) pointing to content type A. 
When current user is at "node/add/typeB/nid_of_type A" page then how can i check the database if he has already created a B node for that A node?

I am trying the following code in my template php:

function theme_name_form_alter(&amp;$form, &amp;$form_state, $form_id) {
if($form_id == 'b_node_form') {
global $user;
if (arg(0) == 'node') {
 $nid = arg(3);
}
$query = db_select('node', 'n')
-&gt;condition('type', 'b', '=')
-&gt;condition('uid', $user-&gt;uid, '=');
$query-&gt;join('field_data_field_a_ref', 'ar', 'n.nid = ar.entity_id');
//field_a_ref is the node reference field from B to A type
$query-&gt;condition('field_a_ref_nid', $nid, '=');
$query-&gt;groupBy('ar.entity_id')-&gt;execute();
if(!empty($query)) {
drupal_goto('/');

    } else {

   }
  }
 }


But i get this error:


  PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM node n INNER JOIN field_data_field_a_ref ar ON n.nid = ar.entity_id W' at line 1: SELECT FROM {node} n INNER JOIN {field_data_field_a_ref} ar ON n.nid = ar.entity_id WHERE (type = :db_condition_placeholder_0) AND (uid = :db_condition_placeholder_1) AND (field_a_ref_nid = :db_condition_placeholder_2) GROUP BY ar.entity_id; Array ( [:db_condition_placeholder_0] => vote [:db_condition_placeholder_1] => 1 [:db_condition_placeholder_2] => 7 ) in theme_name_form_alter() (line 109 of C:...\sites\all\themes\theme_name\template.php).


Any help?
Took a while to spot this, but you're not selecting any fields in the query so the SQL syntax here SELECT FROM {node} n is invalid.

Just select a field and you should be fine:

$query = db_select('node', 'n')
  -&gt;fields('n', array('nid'))
  -&gt;condition('type', 'b', '=')
  -&gt;condition('uid', $user-&gt;uid, '=');