寻找包含特定数据的字段名称(mySql)

时间:2016-01-14 21:53:58

标签: mysql

我的桌子名为" teachers_db"字段名称:

// Assume `mask` is given.
int cpu;
for_each_cpu(cpu, mask)
{
    printk("Allowed CPU: %d\n", cpu);
}

在我的课程中,我获得了教师名单以及他们教授的仪器。 e.i:

teacher_name 
instrument1
instrument2 
payment1 
payment2

我想在mySQL中使用Mathew - piano Mathew - drums Adam - guitar teacher_name(乐器1 ="钢琴"或者instrumnet2 ="鼓"等等)的代码行on),并为它返回instrument(如果它是钢琴则为payment1,如果是鼓,则为playment2)。

我正在解决这个问题,请帮忙:)

1 个答案:

答案 0 :(得分:0)

获得结果的一种方法是使用两个单独的查询,并结合UNION ALL运算符。例如:

 SELECT q.teacher_name
      , q.instrument1 AS instrument
      , q.payment1    AS payment
   FROM teachers_db q
  WHERE q.instrument1 <> ''
  UNION ALL
 SELECT r.teacher_name
      , r.instrument2 AS instrument
      , r.payment2    AS payment
  WHERE r.instrument2 <> ''
 ORDER BY 1,2

另一种方法:

SELECT t.teacher_name
     , CASE i.n WHEN 1 THEN t.instrument1 WHEN 2 THEN t.instrument2 END AS instrument
     , CASE i.n WHEN 1 THEN t.payment1    WHEN 2 THEN t.payment2    END AS payment
  FROM (SELECT 1 AS n UNION ALL SELECT 2) i
 CROSS
  JOIN teachers_db t
HAVING instrument <> ''
 ORDER BY 1,2