我希望将一个表中的行与另一个表中的行匹配,并且每行应该只匹配一次。我构建了下面的查询,在所有其他方面都可以正常工作,除了我没有进一步调整它以便只能选择一行。
try{$results_pref_school1 = $db->query('SELECT mps.mps_client_ec_no, mcs.mcs_client_ec_no, mps.mps_school_id, mcs.mcs_school_id
FROM match_pref_schools AS mps
INNER JOIN match_current_schools AS mcs
ON mps.mps_school_id = mcs.mcs_school_id
AND mcs.mcs_id IN (SELECT MIN(mcs.mcs_id)
FROM match_current_schools AS mcs
GROUP BY mcs.mcs_school_id)
ORDER BY mcs.mcs_id');
}catch (Exception $e){
echo 'Failed to retrieve matched preferred school';
exit;
}
$matched_school = $results_pref_school1->fetchAll(PDO::FETCH_ASSOC);
$ matched_school的var_dump产生:
Array
(
[1] => Array
(
[mps_client_ec_no] => REG5
[mcs_client_ec_no] => GL98888
[mps_school_id] => 6
[mcs_school_id] => 6
)
[2] => Array
(
[mps_client_ec_no] => TAS4752
[mcs_client_ec_no] => ALF1252
[mps_school_id] => 14
[mcs_school_id] => 14
)
[3] => Array
(
[mps_client_ec_no] => MAP002
[mcs_client_ec_no] => ALF1252
[mps_school_id] => 14
[mcs_school_id] => 14
)
)
在上面的结果中,我希望ALF1252只匹配一次。
答案 0 :(得分:0)
@Parts 希望这对您的查询有帮助
在此我添加了索引键,用于删除“使用where;使用连接缓冲区(Block Nested Loop)”,并添加一个 匹配的行和您的查询效果现在最好。
QUERY:
SELECT mps.mps_client_ec_no,mps.mps_school_id, mcs.mcs_client_ec_no, mcs.mcs_school_id
FROM match_pref_schools AS mps INNER JOIN match_current_schools AS mcs
ON mps.mps_school_id = mcs.mcs_school_id
where mcs.mcs_id IN (SELECT MIN(mcs.mcs_id)
FROM match_current_schools AS mcs
GROUP BY mcs.mcs_school_id)
ORDER BY mcs.mcs_id
索引:
KEY `mcs-key` (`mcs_school_id`,`mcs_id`,`mcs_client_ec_no` ) KEY `mps-key` (`mps_school_id`,`mps_client_ec_no`)
INSERT INTO match_current_schools (
mcs_id
,mcs_client_ec_no
,mcs_school_id
,mcs_distr_id
,mcs_province_id
,mcs_client_level_taught
,mcs_sub1_id
,mcs_sub2_id
)VALUES(6,'XYZ',1,27,3,'HIGH SCHOOL - A LEVEL',1, 9);