1

我有这个 sql 字符串:

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() "

我想做的是:我想从表“食物”中输入值“FName”到一个文本框,其中表“类别”的“ID”字段为 1。

我有 3 张桌子。第一个是餐桌食品,第二个是餐桌类别,第三个是 foodCategory。表 foodCategory 具有从前 2 个表到一对多关系的 ID。我收到以下错误:JOIN 附近的语法不正确。我做错了什么?

4

4 回答 4

3

您的查询不正确,必须在 FROM 子句中设置 JOIN,而不是在 WHERE 子句中。

于 2012-06-12T16:19:40.243 回答
1

尝试以下查询

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() "

此外,您应该查看Parameter因为您的代码很容易受到SQL 注入的影响!

于 2012-06-12T16:20:45.390 回答
0

这可能是你的串联:

... foodCategory.Food_ID" & "JOIN category ...

将评估为

foodCategory.Food_IDJOIN category
于 2012-06-12T16:19:29.853 回答
0

您的 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() ";
于 2012-06-12T16:23:26.090 回答