我有乐器 list 和教师乐器 list 。
我想获得包含 ID 和名称的完整仪器列表。
然后检查 teachers_instrument 表中的乐器,如果特定教师有乐器,则在新列中添加 NULL
或 1
值。
然后我可以用它来遍历 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 BY
和 COUNT()
来按仪器对结果集进行分组并计算其用户(不包括 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/