坚持用SQL查询

时间:2012-05-26 06:11:25

标签: mysql

我正在处理我的最终项目,这是一个返回所有ID,名称和日期列表的查询。

select 
 c.id as id, i.full_name as n, day as d
 from
 (instructors i
 inner join courses c ON c.instructor_id = i.id)
 inner join exam_schedules e ON c.id = e.course_id

结果samlpe:

id  name    day
9977    SCOTT, RAYMOND C.   wednesday
9467    FERNANDEZ, CYNTHIA E.   wednesday
9468    FERNANDEZ, CYNTHIA E.   wednesday
9493    FERNANDEZ, CYNTHIA E.   wednesday
9538    STEPHENS, RONNIE T. wednesday
9539    MYERS, RONNIE Y.    wednesday
9554    GARRISON, EUGENE A. wednesday

如何获取所有ID的列表以及名称+日组合的数量?

上面的例子应该产生:

9977    1
9467    3
9468    3
9493    3
9538    1
9539    1
9554    1

2 个答案:

答案 0 :(得分:1)

为了清楚起见,我使用了临时表。可以将它合并到一个查询中,但没有真正的模式很难做到:

CREATE TABLE tmp2 ( id int, name_day varchar(80) );

INSERT INTO tmp2 (id, name_day) (SELECT c.id AS id, CONCAT(i.full_name, i.day) AS name_day
     FROM (instructors i
         INNER JOIN courses c ON c.instructor_id = i.id)
         INNER JOIN exam_schedules e ON c.id = e.course_id
         );

SELECT id, counter FROM 
    (SELECT name_day, count(*) AS counter FROM tmp2 GROUP BY name_day) AS t1
    INNER JOIN
    tmp2
    ON t1.name_day = tmp2.name_day;

DROP TABLE tmp2;

答案 1 :(得分:0)

在不了解您的架构的情况下,很难确定什么是最优的查询;但实质是你需要计算子查询中每一天的计数,然后将结果与表连接以产生所需的输出。例如:

SELECT   c.id, ctbl.total
FROM     instructors    AS i
  JOIN   courses        AS c ON c.instructor_id = i.id
  JOIN   exam_schedules AS e ON e.course_id     = c.id
  JOIN (
    SELECT   day
      ,      COUNT(*) AS total
    FROM     instructors    AS i
      JOIN   courses        AS c ON c.instructor_id = i.id
      JOIN   exam_schedules AS e ON e.course_id     = c.id
    GROUP BY day
  ) AS ctbl USING (day)