php - MySQL加入并创建新的列值

标签 php mysql codeigniter

我有乐器 list 和教师乐器 list 。

我想获得包含 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 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 .

关于php - MySQL加入并创建新的列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14817225/

相关文章:

php - 基于日期的年份报表查询

php - 在 Codeigniter 中替换百分比字符

MySQL 选择连接值中的位置

php - ActiveRecord 类的适当模式

php - 如何使 "PHPmailer"在函数中工作

php - 为动态输入数组插入空值

PHP:迭代多个数组并构建 SQL INSERT 查询

image - 当将 2 个不同的图像上传到 2 个不同的文件夹时,将上传图像。但不会创建缩略图

php - 如何使用 jquery 调用 php Controller 方法?

javascript - 单击使用这些 id 在 javascript 中获取此变量