MySQL按群组加入

时间:2017-09-05 11:34:28

标签: mysql left-join

我正在尝试根据得分和年份匹配两个表来查找哪些ID属于一起。我编写了以下示例:

表a:

  id | score | year
  1      0     2000
  1      1     2001
  1      2     2002

表b:

id_match | score_match | year
  10           0         2000
  10           1         2001
  10           2         2002
  20           0         2000
  20           0         2001
  20           2         2002

id_match = 10与id = 1具有相同的分数,而对于id_match = 20,年份= 2001则不同。我想仅匹配在所有年份具有完全相同得分的ID。

输出表可能如下所示:

id | id_match
1      10

我猜这是一个相对简单的查询。我在考虑这样的事情:

SELECT a.id, b.id_match
FROM a
LEFT JOIN b
  ON a.score = b.score
  AND a.year = b.year
GROUP BY a.id, b.id_match;

但是,如果所有年份的id和id_match分数相等,我想要匹配。

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

我想你想要:

package main

import (
    "os"
    "net/http"
    "io"
)

func downloadFile(filepath string, url string) (err error) {

  // Create the file
  out, err := os.Create(filepath)
  if err != nil  {
    return err
  }
  defer out.Close()

  // Get the data
  resp, err := http.Get(url)
  if err != nil {
    return err
  }
  defer resp.Body.Close()

  // Writer the body to file
  _, err = io.Copy(out, resp.Body)
  if err != nil  {
    return err
  }

  return nil
}

func main() {

  var filename string = "urls.txt"
  var url1 string = "http://94.177.247.162:5000/random"

  downloadFile(filename, url1)

}

答案 1 :(得分:0)

试试这个

select a.id, b.id_match from tableA a, tableB b
  where a.score = b.score
    and a.year = b.year
    and b.id_match not in (select b.id_match from tableB b, tableA a
                             where b.score != a.score
                               and b.year = a.year
                            group by b.id_match)
 group by a.id, b.id_match;