MySQL从多个表中查询搜索过滤器

时间:2014-05-27 23:11:05

标签: c# mysql asp.net sql gridview

我有多个表,我有一个搜索ASP.NET页面,其中包含GridView的结果。 GridView必须包含Name,School,State,Country 我有多个表只包含数据:

index_States

indexID| State
----------------
 1     | state1
 2     | state2
 3     | state3

index_Contries

indexID| Country
----------------
 1     | country1
 2     | country2
 3     | country3

index_Schools

indexID| School
----------------
 1     | school1
 2     | school2
 3     | school3

然后我将包含indexID的表作为参考
General_Info

idKey | Name 
--------------
 1    | John
 2    | McClane
 3    | Jr.

Academic_XP

id | idSchool | idState | idCountry | idKey
--------------------------------------------
 1 |    1     |   3     |    20     |  2
 2 |    1     |   5     |    146    |  3
 3 |    2     |   1     |    65     |  9

然后我有包含UserType的表,因为只搜索某种类型的用户 的用户

id | UserType | idKey
-----------------------
 1 |    1     |   1
 2 |    3     |   2
 3 |    3     |   3
 4 |    1     |   4

我已经尝试过多次查询但似乎没有任何查询。 似乎正在运行的最后一个查询是 INNER JOIN

SELECT Name, State
FROM General_Info A, Academic_XP B
INNER JOIN index_States D ON B.idState = D.indexID
GROUP BY A.id;

但是,只要我添加第二个 INNER JOIN WHERE 子句,它就无效

SELECT Name, State
FROM General_Info A, Academic_XP B, Users
INNER JOIN index_States D ON B.idState = D.indexID
INNER JOIN index_School E ON B.idSchool = E.indexID
GROUP BY A.id
WHERE Users.UserType = 3;

我不知道怎么能这样做。 所以我想这个问题是

如何制作一个从所有这些表中返回的查询?

Name    | State  | School  | Country
---------------------------------------
McClane | state3 | school1 | country20 
Jr.     | state1 | school5 | country146

请注意, McClane Jr。都是UserType 3。 我将不胜感激。

1 个答案:

答案 0 :(得分:0)

您在没有连接的表之间生成cartesian product。我认为这是您正在寻找的其他JOINs

SELECT DISTINCT 
       G.Name,
       S.State,
       C.Country,
       SC.School
FROM Academic_XP A
    JOIN Users U ON A.idKey = U.idKey
    JOIN General_Info G ON A.id = G.idKey
    JOIN Index_States S ON A.idState = S.indexID
    JOIN Index_Contries C ON A.idCountry = C.indexID
    JOIN Index_Schools SC ON A.idSchool = SC.indexID
WHERE U.UserType = 3

如果某些表格没有匹配的键,则您需要使用OUTER JOIN