MySQL查询从多个表中搜索过滤器
本文关键字:搜索 过滤器 查询 MySQL | 更新日期: 2023-09-27 18:05:22
我有多个表,我有一个搜索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。
在没有连接的表之间生成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
。
- SQL join的可视化解释