设置:
create table main(id integer unsigned);
create table test(id integer unsigned,created datetime,text text);
insert into main value(1);
insert into test value(1,now(),'something1');
insert into test value(1,now() + interval 1 day,'something2');
使用:
select main.id, text from main left join test on main.id=test.id
group by main.id where main.id in (1,2,3);
返回:
+------+------------+
| id | text |
+------+------------+
| 1 | something1 |
+------+------------+
如何获得
+------+------------+
| id | text |
+------+------------+
| 1 | something2 |
+------+------------+
答案 0 :(得分:1)
尝试以下SQL语句:
SELECT id, (
SELECT text
FROM test
WHERE test.ID = main.ID
ORDER BY created DESC
LIMIT 0 , 1
) AS text
FROM main
编辑:
如果您需要表测试中的多个列,则需要添加主键。然后,在您的查询中,首先获取主键列并将其用作以下子查询的参考:
# Add the primary key
ALTER TABLE `test` ADD `test_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST ;
# Select many columns
SELECT id, (
SELECT test_id
FROM test
WHERE test.ID = main.ID
ORDER BY created DESC
LIMIT 0 , 1
) AS testID, (
SELECT text
FROM test
WHERE test_id = testID
) AS text, (
SELECT created
FROM test
WHERE test_id = testID
) AS created
FROM main
答案 1 :(得分:0)
已编辑:
这个怎么样?
select
main.id, a1.created,a1.text
from
main
inner join test a1 on
a1.id = main.id
LEFT OUTER JOIN test a2 ON
(a1.id = a2.id
AND (a1.created < a2.created))
WHERE a2.id IS NULL;
答案 2 :(得分:0)
SELECT
main.id , test.created , test.text
FROM
main
JOIN test ON (main.id = test.id)
JOIN (select id,max(created) as created from test group by id) as t2 ON (test.id = t2.id and test.created =t2.created)
答案 3 :(得分:-1)
select id, text from main left join test on main.id=test.id order by created
您可能需要使用ASC(结束)或DESC(结束)