2017-07-31 2 views
0

J'ai les tables 'post' et 'comment'. Je veux sélectionner derniers 3 postes et tous les commentaires pour ce messages. Curently j'utilise 2 déclarations distinctes:Ligne LIMIT avec jointure à gauche

SELECT p.* FROM post p ORDER BY p.date DESC LIMIT 3; // called 1 
SELECT c.* FROM comment c WHERE c.post_id = :id; // called 3x time for each post. 

Il est possible de mariner ces requêtes en un?

Répondre

3

Vous pouvez utiliser une sous-requête pour l'ensemble des messages:

SELECT p.* 
FROM (SELECT p.* 
     FROM post p 
     ORDER BY p.date DESC 
     LIMIT 3 
    ) p JOIN 
    comment c 
    ON c.post_id = p.id 
ORDER BY p.id, c.id; 
+0

Works, sans aucun problème. –

1
SELECT POST .*, COMMENT.* 
from POST INNER JOIN COMMENT ON POST.id = COMMENT.post_id 
where POST.id = COMMENT.post_id ORDER BY POST.id LIMIT 3 
+0

Cela ne fonctionnera pas. Peu importe quoi, nous obtenons toujours seulement 3 enregistrements. –

1

Vous pouvez également essayer cette

SELECT p . * , c . * 
FROM post p 
LEFT JOIN 
COMMENT c ON c.post_id = p.id 
where p.id IN (SELECT id from post order by date desc limit 3) ORDER BY p.date 
+0

Fonctionne. Votre code m'amène à l'erreur SQL (1235): Cette version de MySQL ne supporte pas encore la sous-requête 'LIMIT & IN/ALL/ANY/SOME'. Mais petite recherche: https://stackoverflow.com/questions/17892762/mysql-this-version-of-mysql-doesnt-yet-support-limit-in-all-any-some-subqu et problème disparu. Fonctionne parfaitement. –