简体   繁体   中英

Multiple MYSQL Inner Joins

Hi I am trying to create a search function but having trouble on getting it to work.

This is what I have so far:

SELECT DISTINCT users.ID, users.name

FROM users 
INNER JOIN usersSkills 
ON users.ID = usersSkills.userID 
INNER JOIN usersLanguages 

ON users.ID = usersLanguages.userID 
WHERE activated = "1" 
AND type = "GRADUATE" 

AND usersSkills.skillID IN(2) 
GROUP BY usersSkills.userID HAVING COUNT(*) = 1 

AND usersLanguages.languageID IN(2) 
GROUP BY usersLanguages.userID HAVING COUNT(*) = 1 

But I keep getting this 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 'GROUP BY usersLanguages.userID HAVING COUNT(*) = 1' at line 14

If i remove one of the inner joins and group bys it works so not sure what it is can i use two group bys?

You have two group by clauses in the statement; that is invalid SQL . Do your first group by, then a comma, then your second group by. Your Having clauses should come after using ORs and ANDs to join them into a logical statement

GROUP BY usersSkills.userID, usersLanguages.userID
HAVING COUNT(*) = 1 
AND usersLanguages.languageID IN(2) 

that answers your syntax error question.. (not trying to speak down here) but the structure of the query shows you don't really know what you want to do in the form of the query though... I would strongly suggest you get a SQL book or go through a sql tutorial so you understand what the statements you are trying to write actually do..

Tr this:

SELECT DISTINCT users.ID, users.name, COUNT(*)
FROM users 
INNER JOIN usersSkills ON users.ID = usersSkills.userID 
INNER JOIN usersLanguages ON users.ID = usersLanguages.userID 
WHERE activated = "1" 
      AND type = "GRADUATE" AND usersSkills.skillID = 2 
      AND usersLanguages.languageID = 2 
GROUP BY usersSkills.userID,
         usersLanguages.userID 
HAVING COUNT(*) = 1 

Removed the multiple erroneous GROUP BY 's and merged the query.
Also changed the IN(x) to = x

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