MySql 쿼리 방법 도와주세요

thisrule의 이미지

MySql에서 이런 경우 한번에 쿼리할 수 있는 방법에 대하여 조언을 구합니다.

table의 description이 학년, 학생, 국어, 영어, 수학, 총점, 평균 이라고 하고 (table name=students)
여러 data가 들어있을때
'각 학년에서 제일 평균이 높은 학생을 표시하라'라고 한다면 어떻게 해야하나요?

제가 해본건
select 학년,max(평균) from students group by 학년;
이렇게 하면 각 학년의 최고 평균 점수가 나오고, 그 점수를 다시
select * from students where 학년=1 and 평균='아까구한최고평균';
이렇게 하면 될거같긴한데, 쿼리를 7번이나 해야합니다.

한번에 할 수 있는 방법이 없을까요?

lacovnk의 이미지

group by
order by

thisrule의 이미지

group by, order by로 어떻게 하란 말씀인지요?
저도 group by를 사용했었는데요...

lacovnk의 이미지

어이쿠~ 그러게요 :)

order by 해서 묶으면 max인 녀석을 선택할 줄 알았더니 그렇지 않군요. 죄송합니다.

이번 기회에 배우고 가네요. 감사합니다. :)

select 결과를 table로 사용할 수 있습니다. 뭐라고 하더라.. nested query라고 하던가? -_-

select bla from table_name, (select blabla...) as bla_table where blabla...

:)

익명 사용자의 이미지

select
max(case 학년 when '1학년' then 평균 else 0 end ) s1,
max(case 학년 when '2학년' then 평균 else 0 end ) s2,
max(case 학년 when '3학년' then 평균 else 0 end ) s3,
max(case 학년 when '4학년' then 평균 else 0 end ) s4
from 학생

thisrule의 이미지

제가 예를 잘못들었나 봅니다. 제가 원하는 답변이 아닙니다.
제가 예를 1~6학년으로 해서 6개의 그룹밖에 없다면 case문을 사용하겠지만
만약 그룹이 6개가 아닌 50개 이상이거나 또는 그룹의 개수가 명확하지 않다면
어떻게 해야하나요?

nested query를 사용하려 했으나 select xxx from table1 where select yyy from table2...
에서 뒤쪽의 select 결과가 하나일때만 사용가능하더군요.

더 좋은 방법을 알고 계신분들의 조언을 바랍니다.

ironboy의 이미지

MS-SQL에서는 실행될듯한데요...
아마 MySQL에서도 되지 않을까.. 싶네요.

select 학년, 학생
from
(
select 학년, max(평균) as 평균 from students group by 학년
) a,
students s
where s.평균 = a.평균 and s.학년 = a.학년

thisrule의 이미지

가능해보여 바로 실행해 보았습니다.
결과가 주르륵 잘 나옵니다...만, 뭔가 이상해서 다시 보니 원하는 결과가 아닙니다.

제가 원하는 결과는 각 학년별 1등의 모든 record를 다 출력해 보고 싶었습니다. 아래와 같이요.
=================================
학년 이름 국어 수학 영어 평균
=================================
1 홍길동 95 100 100 98.3
2 변사또 100 95 100 98.3
...
...
=================================

그런데 ironboy님의 결과는 이렇습니다.
=================================
학년 평균
=================================
1 98.3
2 98.3
...
...
=================================

즉 a로 묶은 select문만을 수행한 결과와 동일합니다.
생각해보니 from 뒷부분의 결과에서는 field가 학년과 평균밖에 없는 상태이므로 그 table에서
원래 students의 다른 field는 추출이 되질 않더군요. 쩝...

어떻게 될거 같은데 잘 안되네요. 흑흑...

ironboy의 이미지

select s.*
from
  (select 학년, max(평균) as 평균 from students group by 학년) a,
  students s
where s.평균 = a.평균 and s.학년 = a.학년

이렇게 다시 한번 해 보시는 것이 좋을 듯 합니다.

students의 다른 필드는 출력이 될겁니다.
(join을 한 것이니..)

thisrule의 이미지

정말 감사합니다. 잘 됩니다.(시간이 좀 걸리네용...)
새로운걸 알겐된 기쁨도 큽니다.
ironboy님 행복하세요...^-^

lacovnk의 이미지

별로 복잡해보이지 않는 쿼리도 생각보다 오래걸립니다. 인덱스를 걸어주거나, 아니면 nest 안 부분을 임시 테이블에다가 insert하고 join하면 성능이 나을겁니다.

예전에 블로그에서 댓글 없는 포스트의 뭐를 찾느라 nest 써본 적이 있는데.. 정말 느리더군요 -_-

익명 사용자의 이미지

이런 sql도 mysql에서 실행이 되나요?

select *
from student
where (학년, 평균) in (select 학년, max(평균) from student group by 학년)

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.