2016-04-20 15 views
1

Kommentar Tabellemysql verbinden linke Seite mit Limit 0,2

+------+----------+ 
| id | comment | 
+------+----------+ 
| 1 | foo  | 
| 2 | bar  | 
| 3 | foobar | 
+------+----------+ 

Antwort Tabelle

+------+----------+------------+ 
| id | reply |comment_id | 
+------+----------+------------+ 
| 1 | nice lol | 1   | 
| 2 | ok ok | 2   | 
| 3 | hello | 1   | 
| 4 | hello2 | 1   | 
| 5 | hello1 | 1   | 
+------+----------+------------+ 



SELECT 
`comment`.`comment`, 
`x`.`reply` 
FROM `comment` LEFT JOIN 
(SELECT GROUP_CONCAT(`reply`) as reply ,reply.commnt_id FROM `reply` 
GROUP BY `reply`.`comment_id` ORDER BY `reply`.`id` LIMIT 0,1)x ON x.comment_id = comment.id 

das Ergebnis

+----------+-----------------+ 
| comment | reply   | 
+----------+-----------------+ 
| foo | nice lol,hello | 
| bar | NULL   | 
| off | null   | 
+------+---------------------+ 

die Frage sein, warum der zweite Kommentar haben null, aber wenn Ich mache Limit 0,4 wird es zeigen

+0

versuchen Sie für jeden Kommentar Top 2 Antworten zu zeigen? –

+0

@ShekharJoshi ja –

+1

Es könnte sich herausstellen, dass die korrekte Schreibweise 'reply' nicht 'replay' ist. Wenn Sie ein Team haben, werden Sie sich dafür bedanken! – Arth

Antwort

3

Mysql unterstützt keine Begrenzungen in der group by-Klausel. Um diese Art der Funktion erreichen können, wir hacken Group_concat wie unten dargestellt:

SELECT 
comment.comment, 
x.replay 
FROM comment LEFT JOIN 
(SELECT 
    REPLACE(substring_index(group_concat(replay SEPARATOR '@@'), '@@', 2), '@@', ',') as replay ,replay.commnt_id 
    FROM replay 
    GROUP BY replay.comment_id ORDER BY replay.id LIMIT 0,1)x 
ON x.comment_id = comment.id 

dies bedenkt, dass Ihre Antworten werden nicht haben ‚@@‘ in ihnen.

related posts:

GROUP_CONCAT with limit

Mysql group_concat limit rows in grouping

+0

danke seine Arbeit :) –