【问题标题】:MySQL Join and create new column valueMySQL加入并创建新的列值
【发布时间】:2013-02-11 17:14:01
【问题描述】:

我有一个乐器清单和教师乐器清单。

我想获得带有 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

【问题讨论】:

  • teachers_instruments 中的代理键有什么意义?
  • 抱歉,您的问题有点含糊。您是否要计算使用每种乐器的教师人数?然后 LEFT 加入您的 ti 表并使用 COUNT(teacher_id) 进行计数。
  • 我猜是不需要的。
  • 我更新了帖子,希望对您有所帮助。

标签: php mysql codeigniter


【解决方案1】:

一种可能的方法:

    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;

Demo.

【讨论】:

  • 太棒了!如何仅为 1 个用户添加 where 子句 (WHERE ti.teacher_id = X)?
【解决方案2】:

嗯,可以这样实现

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。

【讨论】:

    猜你喜欢
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多