2012-07-06 59 views
2

我有兩個表SchoolsUsersMySQL來獲取相關用戶

表學校

----------------------------------------------------- 
| id |  name | city |  major | userID | 
----------------------------------------------------| 
| 1 | school A | chicago | CS  | 1 | 
----------------------------------------------------| 
| 2 | school B | chicago | CS  | 1 | 
----------------------------------------------------| 
| 3 | school A | chicago | CS  | 2 | 
----------------------------------------------------| 
| 4 | school C | chicago | Art  | 2 | 
----------------------------------------------------| 
| 5 | school B | chicago | CS  | 3 | 
----------------------------------------------------| 
| 6 | school D | chicago | Math  | 3 | 
----------------------------------------------------| 
| 7 | school A |New York | CS  | 3 | 
----------------------------------------------------| 
| 8 | school B | chicago | Art  | 3 | 
----------------------------------------------------- 

表用戶

-------------------- 
| id |  name | 
____________________ 
| 1 | User A | 
____________________ 
| 2 | User B | 
____________________ 
| 3 | User C | 
____________________ 
| 4 | User D | 
____________________ 
| 5 | User E | 
____________________ 

schools表中的userID字段是一個外鍵id字段在users表中。我想編寫一個MySQL語句,它需要一個給定的userID並列出該用戶的所有同學。

因此,對於上面的例子中,User A(ID#1)的一類伴侶是去到同一學校作爲User A用戶,位於同一city,並且具有相同的major。因此,User A的有效同學只有User B(ID#2)和User C(ID#3)。

現在,我正在使用兩個MySQL語句來實現此目標。第一個是

SELECT id FROM schools WHERE userID = '1' 

其中列出所有學校爲User A。然後,我經歷的結果,併爲每個我跑行使用PHP來循環以下

SELECT userID from schools WHERE 
name city LIKE '%$chicago%' 
AND name LIKE '%$school A%' 
AND major LIKE '%$CS%' 

這工作得很好,並返回用戶ID的右側列表。但是,我想知道是否有一種更有效的方法在一個SQL語句中執行此操作,而無需使用PHP。

+4

請重新設計您的表格。他們沒有正常化,可能會陷入許多致命的事情....看到這裏:http://stackoverflow.com/a/11363740/561731和相關評論下的OP – Neal 2012-07-06 15:56:45

+0

這是另一個可能有所幫助的評論:http:///stackoverflow.com/questions/11363688/mysql-select-women-not-men/11363740#comment14970233_11363688 – Neal 2012-07-06 15:59:13

回答

2

你可以這樣說:

select distinct u.name 
from Users u 
join School s on s.userID = u.id 
join (
      select distinct s.name, s.city 
      from School s 
      inner join Users u on u.id = s.userID 
      where u.name = 'User A' 
      ) aux on s.name = aux.name and s.city = aux.city 
where u.name <> 'User A' 

aux查詢您所選擇的name的和city'的@user和則s選擇所有users上述要求,不屬於@user本身。

您可以用變量替換'用戶A'。

-2

你的學校表不被認爲是正確的。它違反了關係數據庫管理系統的規則。

我們必須製作3張表格:一個用於學校名稱,另一個用於城市名稱,第三個用於主要名稱。所有這些都必須是帶有ID的不同表格。

很明顯,名稱列和城市列具有多對多的關係,因此必須爲此查找表。

同樣適用於主欄。看起來好像很多表格,但是你提取任何值都很簡單。

好的,我對錶格做了一些修改。我更喜歡這種方式來存儲數據:

table student 
col. 
id 
name 
major 
reg.no. (to make each student unique) 

table school 
col. 
id 
name 

table city 
col. 
id 
name 

table student_school (lookup table) 
col. 
student_id 
school_id 

table school_city 
col. 
school_id 
city_id 

首選這些表,你會發現每個查詢都可以輕鬆完成。如果您在理解這方面有任何問題,請告訴我。

+0

我不得不在這個答案上做很多工作,以使它清晰易讀,所以在將來,你可以按照這種格式回答?尤其是,如果您不使用像「你」這樣的文字的文字縮寫,比如「你的」,我們更喜歡。 – 2012-07-08 04:45:35