简体   繁体   中英

Error in MySql syntax on INNER JOIN use

I'm trying to check if a username it was already chosen. Before of show the query this is my tables structure:

USER

ID | data

 5    0
 6    1

USERS_SETTINGS

ID | Username

 5    Dillinger
 6    John

How you can see in the table user I've a list of all users available in the system and in the users_settings table I've the settings of each user of user table. Now if a customer who is registering in the system chose the username Dillinger an error message appear 'cause the username has already chosen, instead, if the customer chose John the system doesn't show any error 'cause there was already a registered user with the username but was deleted data: 1 . What I tried:

query = "SELECT Count(username) from users_settings u
                                INNER JOIN user id d ON
                                u.id = d.id
                                WHERE u.username = @usernamep AND
                                d.data = @datap"

But when I do .ExecuteScalar I get:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use neare 'd ON u.id = d.id 'at line 2

What is wrong exactly?

This fixes the problem with the syntax:

select count(*)
from user u join
     user_settings us
     on u.id = us.id -- I am guessing about the right column name here
where u.username = @usernamep and us.data = @datap;

However, this is more expensive than it might need to be. A cheaper method uses exists rather than count() :

select 1
from user u
where u.username = @usernamep and
      exists (select 1
              from user_settings us
              where u.id = us.id and us.data = @datap
             )
limit 1;

A user already exists if this returns any rows. For best performance, you want an index on user(username) and user_settings(user_id, data) .

You seems to assign two different alias (or a typo) to a table which is not valid and should be changed to :

query = "SELECT Count(username) 
         FROM users_settings u INNER JOIN user d 
         ON u.id = d.id
         WHERE u.username = @usernamep 
         AND   d.data = @datap"

try this

query = "SELECT Count(username) from users_settings u
                            INNER JOIN user d ON
                            u.id = d.id
                            WHERE u.username = @usernamep AND
                            d.data = @datap"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM