1

I am trying to create a 3 way join between marks, messages, and votes. I tried to model the other posts on this particular query, but it does not seem to work:

Error

[Error: ER_PARSE_ERROR: 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 'LEFT JOIN votes ON votes.messageId = messages.id ORDER BY timestamp DESC' at line 1]

Here is my query:

 var query = ([
    'SELECT * FROM marks',
    'LEFT JOIN messages',
    'ON marks.messageId = messages.id',
    'WHERE marks.x between ? AND ?',
    'AND marks.y between ? AND ?',
    'LEFT JOIN votes',
    'ON votes.messageId = messages.id',
    'ORDER BY timestamp DESC'
]).join(' ');

Schema

CREATE TABLE marks (
  id int(5) AUTO_INCREMENT,
  PRIMARY KEY (id),
  x float(10, 6),
  y float(10, 6),
  z float(10, 6),
  timestamp timestamp DEFAULT CURRENT_TIMESTAMP,
  messageId int(5),
  FOREIGN KEY (messageId) REFERENCES messages(id),
  userToken VARCHAR(255),
  FOREIGN KEY (userToken) REFERENCES users(token)
);

CREATE TABLE messages (
  id int(5) AUTO_INCREMENT,
  PRIMARY KEY (id),
  messageString text,
  score int(5) DEFAULT 0
);

CREATE TABLE votes (
  id int(5) AUTO_INCREMENT,
  PRIMARY KEY(id),
  userToken VARCHAR(255),
  FOREIGN KEY (userToken) REFERENCES users(token),
  messageId int(5),
  FOREIGN KEY (messageId) REFERENCES messages(id)
);
Community
  • 1
  • 1
chopper draw lion4
  • 12,401
  • 13
  • 53
  • 100

3 Answers3

2

Try this:

var query = ([
    'SELECT * FROM marks',
    'LEFT JOIN messages',
    'ON marks.messageId = messages.id',
    'LEFT JOIN votes',
    'ON votes.messageId = messages.id',
    'WHERE marks.x between ? AND ?',
    'AND marks.y between ? AND ?',
    'ORDER BY timestamp DESC'
]).join(' ');

The WHERE clause has to to be after the JOINS.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
1

You need to put the join statements before your where filter, like so:

var query = ([
   'SELECT * FROM marks',
   'LEFT JOIN messages',
     'ON marks.messageId = messages.id',
   'LEFT JOIN votes',
     'ON votes.messageId = messages.id',
   'WHERE marks.x between ? AND ?',
   'AND marks.y between ? AND ?',
   'ORDER BY timestamp DESC'
]).join(' ');
APTy
  • 31
  • 4
0

Your JOIN clauses have to be grouped together, and your WHERE clause has to be after both of them.

This should work for you:

var query = ([
  'SELECT * FROM marks',
  'LEFT JOIN messages',
  'ON marks.messageId = messages.id',
  'LEFT JOIN votes',
  'ON votes.messageId = messages.id',
  'WHERE marks.x between ? AND ?',
  'AND marks.y between ? AND ?',
  'ORDER BY timestamp DESC'
]).join(' ');
Pavlin
  • 5,390
  • 6
  • 38
  • 51