I have this sql string:
Dim sqlQuery As String = "SELECT TOP 1 ID, FName, FoodGroup, Calories, Protein, Carbohydrates, Fat, category.ID" &
" FROM food where Protein<='" & txtProt.Text.ToString() & "' and FoodGroup = 4 " & "and category.ID = 1 " & "JOIN foodCategory ON food.ID = foodCategory.Food_ID" & "JOIN category ON foodCategory.Category_ID = category.ID " & "ORDER BY NEWID() "
What i want to do is this: I want to type the value "FName" from table "food" to an textBox where the "ID" field of table "category" is 1.
I have 3 tables. The first is table food, the second one is table category and the third one is foodCategory. The table foodCategory has the ID's from the first 2 tables to a one-to-many relationship. I get the following error : Incorrect syntax near JOIN. What do i do wrong?
如果查询不正确,则必须在FROM子句中设置JOIN,而不是在WHERE子句中设置JOIN。
Try the following query
dim sqlQuery As String
sqlQuery = "SELECT TOP 1 ID, FName, FoodGroup, Calories, Protein, " & _
"Carbohydrates, Fat, category.ID " &_
"FROM food JOIN foodCategory ON " & _
"food.ID = foodCategory.Food_ID JOIN category ON " & _
"foodCategory.Category_ID = category.ID " & _
"where Protein<='" & txtProt.Text.ToString() & "' and " & _
"FoodGroup = 4 and category.ID = 1 " & _
"ORDER BY NEWID() "
Furthermore you should have look at Parameter as your code is very vulnerable to SQL injection !
It's probably your concatenation:
... foodCategory.Food_ID" & "JOIN category ...
would evaluate to
foodCategory.Food_IDJOIN category
您的JOIN必须在WHERE子句之前:
" FROM food" & " JOIN foodCategory ON food.ID = foodCategory.Food_ID" & "JOIN category ON foodCategory.Category_ID = category.ID " & " WHERE Protein<='" & txtProt.Text.ToString() & "' and FoodGroup = 4 " & "and category.ID = 1 " & " ORDER BY NEWID() ";
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.