簡體   English   中英

MySQL Join並創建新的列值

[英]MySQL Join and create new column value

我有樂器清單和老師樂器清單。

我想獲取帶有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

好吧,這樣可以實現

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。 如果找到,則將Value設置為1否則為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 (表的命名有些不同)。

說明:在instrument_id上使用LEFT JOIN ,我們將為每個樂器獲得與使用它的老師一樣多的teacher_id值-如果沒有人使用,則只有一個NULL值。 下一步是使用GROUP BYCOUNT()將結果集按工具分組並計算其用戶(不包括NULL值的行)。

如果要顯示所有樂器,並顯示一些標志來表明教師是否正在使用它,則需要另一個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;

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM