2012-11-27 62 views
1

我似乎無法想出製作聯接語句。在其他語句中使用SQL查詢的結果

select usrs.* 
from 
    students s 
    join system_users usrs on 
     s.father=usrs.user_id 
     OR s.mother=usrs.user_id 
     OR s.guardian=usrs.user_id 
where s.user_id = '201209083' 

我有這樣的查詢,並返回:

+------------+---------+--------+--------+ 
| user_id | contact | status | rights | 
+------------+---------+--------+--------+ 
| f201209083 | 4093 | active | NULL | 
| g201209083 | 4095 | active | NULL | 
| m201209083 | 4094 | active | NULL | 
+------------+---------+--------+--------+ 

現在我需要的是使用的聯繫人欄的信息來獲取更多的信息和與此表參加吧:

select 
    * 
from 
    address 
where 
    contact_id = (contact column); 

我需要在一個查詢中實現它的幫助。

P.S.有人能告訴我這種技術被稱爲什麼嗎?我無法通過搜索JOIN來找到相關信息。或者學習的鏈接會更好。

回答

1

你可能會採取目前的語句作爲一個子查詢並加入它是這樣:

SELECT * FROM address 
JOIN (
    SELECT 
     usrs.* 
    FROM 
     students s 
     JOIN system_users usrs ON s.father=usrs.user_id OR s.mother=usrs.user_id OR s.guardian=usrs.user_id 
    WHERE 
     s.user_id = '201209083' 
) AS temp 
ON contact_id = (contact column); 

這應該給你原始的結果與從address表中的結果相結合。

+0

這正是我需要的!謝謝:) – Cartman

1

一旦你在一個連接有多個表,您可以繼續加入到多個表,就像這樣:

Select a.*,usrs.* 
from students s 
join system_users usrs on s.father=usrs.user_id OR s.mother=usrs.user_id OR s.guardian=usrs.user_id 
join addresses a on a.contact_id=usrs.contact 
where s.user_id = '201209083' 
+0

你的答案只顯示最後一個查詢的結果。我需要將兩個表連接在一起。 – Cartman

+1

@Cartman您可以在投影中添加'usrs。*'以獲得您想要的結果。 – dasblinkenlight

1

一個選項是改變的第一個語句只返回你正在評估對列:

select usrs.contact 
from 
    students s 
    join system_users usrs on 
     s.father=usrs.user_id 
     OR s.mother=usrs.user_id 
     OR s.guardian=usrs.user_id 
where s.user_id = '201209083' 

...然後使用作爲評估CONTACT_ID條件:

SELECT 
    * 
FROM 
    address 
WHERE 
    contact_id IN (
     SELECT usrs.contact 
     FROM 
      students s 
      JOIN system_users usrs ON 
       s.father=usrs.user_id 
       OR s.mother=usrs.user_id 
       OR s.guardian=usrs.user_id 
     WHERE s.user_id = '201209083' 
    ) 

這通常稱爲子查詢或子查詢,自4.1開始,它是supported in MySQL。如果contact_id匹配內部查詢返回的任何值,則"IN" predicate將爲true。

+0

我想我需要用'IN'來提高自己的知識水平。感謝:D – Cartman

+0

很高興提供幫助。你可以嘗試一些簡單的事情,比如'SELECT * FROM address WHERE contact_id IN(4093,4094,4095)'來感受發生了什麼。子查詢只是動態地生成列表。 – GargantuChet