MySQL Join and create new column value

余生长醉 提交于 2020-06-13 00:10:09

问题


I have an instrument list and teachers instrument list.

I would like to get a full instrument list with id and name.

Then check the teachers_instrument table for their instruments and if a specific teacher has the instrument add NULL or 1 value in a new column.

I can then take this to loop over some instrument checkboxes in Codeigniter, it just seems to make more sense to pull the data as I need it from the DB but am struggling to write the query.

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  

my query would look like this:

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

回答1:


One possible approach:

    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;

Here's SQL Fiddle (tables' naming is a bit different).

Explanation: with LEFT JOIN on instrument_id we'll get as many teacher_id values for each instrument as teachers using it are - or just a single NULL value, if none uses it. The next step is to use GROUP BY and COUNT() to, well, group the result set by instruments and count their users (excluding NULL-valued rows).

If what you want is to show all the instruments and some flag showing whether or now a teacher uses it, you need another 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.




回答2:


Well this can be achieved like this

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

Add a column and check for teacher_instrument_id. If found set Value to 1 else 0.



来源:https://stackoverflow.com/questions/14817225/mysql-join-and-create-new-column-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!