JOIN上的结果重复

时间:2017-12-05 13:30:06

标签: mysql sql node.js express phpmyadmin

这是我的问题:我正在尝试获得课程的所有游戏。班级可以主持游戏,或者在另一个班级中玩游戏。

游戏桌有:guest_class(类的ID)和host_class(类的ID)

类表有:id_class(类的ID)

我试图获得1级游戏的一个例子。 1级只有2场比赛。

id_game: 1, id_class: 1, host_class: 3, guest_class: 1,
id_game: 2, id_class: 1, host_class: 1, guest_class: 6,

为什么我会得到重复的结果?

QUERY

var classID = Number(req.query.searchValue);
var query = `SELECT * FROM games g 
LEFT JOIN classes c ON c.id_class = g.host_class OR c.id_class = g.guest_class 
WHERE ( g.host_class = ? OR g.guest_class = ? )`;
con2.query(query, [classID,classID] , function (err, result) {

RESULT

[ RowDataPacket {
    id_game: 1,
    date: 2017-12-04T23:00:00.000Z,
    host_class: 3,
    guest_class: 1,
    host_score: 34,
    guest_score: 74,
    tournament_id: 0,
    group_id: 1,
    statistics: '',
    incidents: '',
    id_class: 1},
  RowDataPacket {
    id_game: 1,
    date: 2017-12-04T23:00:00.000Z,
    host_class: 3,
    guest_class: 1,
    host_score: 34,
    guest_score: 74,
    tournament_id: 0,
    group_id: 1,
    statistics: '',
    incidents: '',
    id_class: 3},
  RowDataPacket {
    id_game: 2,
    date: 2017-11-30T23:00:00.000Z,
    host_class: 1,
    guest_class: 6,
    host_score: 84,
    guest_score: 57,
    tournament_id: 0,
    group_id: 1,
    statistics: '',
    incidents: '',
    id_class: 1},
  RowDataPacket {
    id_game: 2,
    date: 2017-11-30T23:00:00.000Z,
    host_class: 1,
    guest_class: 6,
    host_score: 84,
    guest_score: 57,
    tournament_id: 0,
    group_id: 1,
    statistics: '',
    incidents: '',
    id_class: 6} ]

2 个答案:

答案 0 :(得分:1)

你会这样尝试吗;

select * from games where id_game IN (
SELECT g.id_game FROM games g 
LEFT JOIN classes c ON c.id_class = g.host_class OR c.id_class = g.guest_class 
WHERE ( g.host_class = ? OR g.guest_class = ? )
group by g.id_game)

答案 1 :(得分:0)

  

我正在努力获得1级的比赛。只有2场比赛是1级。

你不需要加入:

SELECT * 
FROM games g 
WHERE g.host_class = ? OR g.guest_class = ?