Home > database >  Two table one-to-many, left the join, right table only in compliance with article records the first
Two table one-to-many, left the join, right table only in compliance with article records the first

Time:09-27

How to write SQL
The CREATE TABLE ` topic ` (
Unsigned ` id ` int (11) the NOT NULL AUTO_INCREMENT,
` title ` varchar (255) the DEFAULT NULL,
The PRIMARY KEY (` id `)
) ENGINE=InnoDB;

The CREATE TABLE ` comment ` (
` id ` int (10) unsigned NOT NULL AUTO_INCREMENT,
` topicId ` int (11) the DEFAULT NULL,
` comment ` varchar (255) the DEFAULT NULL,
The PRIMARY KEY (` id `)
) ENGINE=InnoDB;

INSERT INTO ` topic ` VALUES (' 1 ', 'topic 1');
INSERT INTO ` topic ` VALUES (' 2 ', 'topic 2');

INSERT INTO ` comment ` VALUES (' 1 ', '1', 't1c1');
INSERT INTO ` comment ` VALUES (' 2 ', '1', 't1c2');
INSERT INTO ` comment ` VALUES (' 3 ', '2', 't2c1');
INSERT INTO ` comment ` VALUES (' 4 ', '2', 't2c2');
INSERT INTO ` comment ` VALUES (' 5 ', '2', 't2c3');

CodePudding user response:

Refers to a variety of methods in next post

http://blog.csdn.net/acmain_chm/article/details/4126306
[for] take N largest record grouping method of solicitation, and scattered points...

CodePudding user response:


Select * from (
SELECT
TMP. Id,
Tmp.com mentId,
@ aid:=TMP. Id as aid,
If (@ aid=TMP. Id, @ rank:=@ rank + 1, @ rank:=1) as rank

The FROM
(
SELECT
Anderson, d,
B.i d commentId
The FROM
The topic of a
LEFT the JOIN ` comment ` b ON Anderson, d=b.t opicId
The ORDER BY b.i d
TMP,
(SELECT @ aid:=null, @ rank:=0) t
F) where f.r ank & lt;=2

CodePudding user response:

Advanced query SELECT

http://www.verejava.com/? Id=1717413210274

CodePudding user response:

Select * from
(select * from topic limit 0, n) - take a conform to the record of the previous article
Left the join the comment on Anderson b d=b.t opicId