2013-02-11 34 views
1

我有一個工具列表和教師工具列表。MySQL加入並創建新列值

我想獲得一個完整的工具列表與id和名稱。

然後檢查teachers_instrument表以瞭解他們的樂器,以及特定教師是否已將樂器的值添加到新列中的NULL1

然後我可以通過這個來循環Codeigniter中的一些儀器複選框,它似乎更有意義,因爲我需要從數據庫中提取數據,但我正在努力編寫查詢。

teaching_instrument_list 

- id 
- instrument_name 

teachers_instruments 

- id 
- teacher_id 
- teacher_instrument_id 

SELECT 
    a.instrument, 
    a.id 
FROM 
    teaching_instrument_list a 
LEFT JOIN 
(
    SELECT teachers_instruments.teacher_instrument_id 
    FROM teachers_instruments 
    WHERE teacher_id = 170 
) b ON a.id = b.teacher_instrument_id 

我的查詢應該是這樣的:

instrument name id value 
--------------- -- ----- 
woodwinds   1 if the teacher has this instrument, set 1 
brass    2  0 
strings   3  1 
+0

'teachers_instruments'中的代理鍵有什麼意義? – Kermit 2013-02-11 17:28:00

+0

對不起,但你的問題有點含糊。您是否想要統計使用每種儀器的教師數量?然後LEFT加入你的'ti'表,並使用COUNT(teacher_id)來完成計數。 – raina77ow 2013-02-11 17:37:03

+0

我想這不是必須的。 – user2062046 2013-02-11 17:38:10

回答

0

一個可行的方法:

SELECT i.instrument_name, COUNT(ti.teacher_id) AS used_by 
     FROM teaching_instrument_list AS i 
LEFT JOIN teachers_instruments AS ti 
     ON ti.teacher_instrument_id = i.id 
    GROUP BY ti.teacher_instrument_id 
    ORDER BY i.id; 

這裏的SQL Fiddle(表名稱有些不同)。

說明:與LEFT JOINinstrument_id我們將用它獲得是每個儀器的教師多達teacher_id值 - 或者只是一個單一的NULL值,如果沒有使用它。下一步是使用GROUP BYCOUNT()來對儀器的結果集進行分組並計數其用戶(不包括空值行)。

如果你想要的是顯示所有的儀表和顯示一個老師是否現在使用它的一些標誌,你需要另一個LEFT JOIN:

SELECT i.instrument_name, NOT ISNULL(teacher_id) AS in_use 
     FROM teaching_instrument_list AS i 
LEFT JOIN teachers_instruments AS ti 
     ON ti.teacher_instrument_id = i.id 
     AND ti.teacher_id = :teacher_id; 

Demo

+0

太棒了!我怎樣才能爲一個用戶添加一個where子句(WHERE ti.teacher_id = X)? – user2062046 2013-02-11 17:53:55

+0

感謝您的時間,這工作完美,現在來研究它! – user2062046 2013-02-11 18:07:33

0

那麼這樣就可以實現這樣的

SELECT 
    id, 
    instrument_name, 
    if(ti.teacher_instrument_id IS NULL,0,1) as `Value` 
from teaching_instrument_list as til 
    LEFT JOIN teachers_instruments as ti 
    on ti.teacher_instrument_id = til.id 

添加一列,檢查teacher_instrument_id。如果發現設置值爲1 else 0.