The minimum row on a join
I have a bit of a strange problem, please examine the following 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 holds 0 or more rows referencing tablea. I want to recall the records in tablea with the record in tableb that has the lowest (MIN) position. So at the moment this is a simple bit of 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
If you run this you will see it output
id namea nameb concat concat
3 c NULL NULL NULL
1 a b b,a 1,2
2 b b b,a 2,1
The first & second row is correct but the third I was expecting nameb to be a and not b. I have tried playing around with MIN but cannot seam to get something that always returns me what I am expecting. Any help appreciated, at the moment I am just having to do 2 queries :(
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)
精彩评论