create table if not exists board(
id_board int unsigned not null auto_increment primary key,
topic varchar(50) not null
)engine=myisam default character set utf8;
create table if not exists txtcomment(
id_comment int unsigned not null auto_increment primary key,
id_board int unsigned not null,
postdate datetime null default null,
txt_comment varchar(100) not null
)engine=myisam default character set utf8;
insert ignore into board values(null,'Hello.'),(null,'Where are you come from?'),
(null , 'Rides for life.');
insert ignore into txtcomment values(null,1,'2015-06-20 12:32:30','hello world!'),
(null,1,'2015-06-21 8:30:10','hello,how areyou?'),
(null,2,'2015-06-10 12:12:30','I come from USA.'),
(null,2,'2015-07-01 23:45:10','No matter where I am from.'),
(null,2,'2015-07-01 12:32:30','I am from Taiwan Taipae.'),
(null,2,'2015-07-02 09:12:41','I lives in Thailand so long times.'),
(null,3,'2015-06-11 04:47:10','Yes,I love to rides.Could you suggest?'),
(null,3,'2015-06-17 14:12:30','Can I join the trip?');
// จากข้อมูลทดสอบด้านบน เราจะเขียนคำสั่งได้ดังนี้
select t1.id_board,t1.topic,t2.id_comment,t2.txt_comment,t2.postdate
from board t1 left join txtcomment t2 using(id_board)
where concat(postdate,':',id_board) in (select concat(max(postdate),':',id_board) from txtcomment group by id_board order by postdate desc)
order by t1.id_board,postdate desc
Quote:
id_board topic id_comment txt_comment postdate
1 Hello. 2 hello,how areyou? June, 21 2015 08:30:10
2 Where are you come from? 6 I lives in Thailand so long times. July, 02 2015 09:12:41
3 Rides for life. 8 Can I join the trip? June, 17 2015 14:12:30
select t1.id_board,t1.topic,t2.id_comment,t2.data
from board t1 left join comment t2 using(id_board)
where concat(date,':',id_board) in (select concat(max(date),':',id_board) from comment group by id_board order by date desc)
order by t1.id_board,date desc
select t1.id_post,t1.topic,t2.id_comment,t2.timecom
from data_board t1 left join data_comment t2 using(id_post)
where concat(timecom,':',id_post) in (select concat(max(timecom),':',id_post) from data_comment group by id_post order by timecom desc)
order by t1.id_post,timecom desc
select t1.id_post,t1.topic,t2.id_comment,t2.timecom
from data_board t1
inner join (
select c1.* from data_comment c1
inner join (
select id_post, max(timecom) maxtime
from data_comment group by id_post
) c2 on c1.id_post=c2.id_post and c1.timecom=c2.maxtime
) t2 using(id_post)
order by timecom desc,t1.id_post
Date :
2015-07-06 06:42:49
By :
Chaidhanan
No. 6
Guest
จาก # 2
ลองย้าย condition จาก where ไป อยู่ใน on ครับ
หรือ หรือ ลองแบบนี้ครับ น่าจะได้.....มั้ง...เห่อๆ Code (SQL)
select * from board
left join
(select comment.* from comment
inner join (select max(id_comment) as m_id_comment,id_board from comment group by id_board) as xx on xx.m_id_comment=comment.id_comment
) as yy on yy.id_board=board.id_board