连接上的最小行

时间:2011-08-26 17:00:52

标签: mysql left-join min

我有一个奇怪的问题,请检查以下SQL

CREATE TABLE `tablea` (
    `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    `name` VARCHAR( 60 ) NOT NULL
) ENGINE = MYISAM ;

CREATE TABLE `tableb` (
    `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    `name` VARCHAR( 60 ) NOT NULL ,
    `refid` INT NOT NULL ,
    `position` INT NOT NULL
) ENGINE = MYISAM ;

INSERT INTO tablea (`id`,`name`) VALUE (1,'a'),(2,'b'),(3,'c');
INSERT INTO tableb (`name`, `refid`, `position`) VALUE ('a', 1, 2),('b', 1, 1);
INSERT INTO tableb (`name`, `refid`, `position`) VALUE ('a', 2, 1),('b', 2, 2);

Tableb包含引用tablea的0行或更多行。我想回忆一下tablea中的记录,其中tableb中的记录具有最低(MIN)位置。所以目前这只是一个简单的SQL。

SELECT 
    a.id, 
    a.name AS namea,
    b.name AS nameb,
    GROUP_CONCAT(b.name),
   CAST(group_concat(b.position) AS CHAR )
FROM tablea AS a
LEFT JOIN tableb AS b
    ON b.refid=a.id
GROUP BY a.id
ORDER BY b.position ASC

如果你运行它,你会看到它输出

id  namea   nameb   concat  concat
3   c   NULL    NULL    NULL
1   a   b   b,a 1,2
2   b   b   b,a 2,1

第一个&第二行是正确的,但第三行我期望nameb是a而不是b。我试过玩MIN但是不能接缝以获得总能让我回想起我所期待的东西。任何帮助表示感谢,目前我只需要进行2次查询:(

1 个答案:

答案 0 :(得分:4)

SELECT 
    a.id, 
    a.name AS namea,
    b.name AS nameb,
FROM tablea AS a
LEFT JOIN tableb AS b
    ON b.refid=a.id AND b.position = (SELECT min(position) FROM tableb b2 WHERE b2.rf_id = a.id)