|
我有多张表: |8 t) R% {, p* |2 a3 ^+ O
post$ E7 u B* o, i Y) G0 n; b2 p7 P
id Name c2 @7 k; I5 O$ z' ^1 l' |
1 post-name1
% V3 b! b# f# M 2 post-name2
* W, E+ J4 c7 K/ O; j( Muser
9 {, s1 m9 L4 ?/ I, y6 R* ~3 d id username
9 M3 h" V& `6 z: z% F8 \0 O, [( ? 1 user1
* { l/ u% B) [* }* ^8 j 2 user2% P; J; L1 [+ Y) s
post_user
# ~$ o. J: @2 i1 i1 u post_id user_id; x( R! W i- D( a
1 14 l; d1 W1 J7 U) @
2 13 [1 T" ?; S8 k0 z/ g6 e; I
post_comments: x! a. P) G5 Z% J
post_id comment_id. i& f2 A: ^& s# X) W
1 16 N) ~, T0 b; V* d) Q
1 21 N7 j( L; n) Z7 S( G
1 3- z# R& y" b' @- x; Q. Y- L* @
我正在使用这样的查询:
$ b8 ~( t* ~, _SELECT post.id, post.title, user.id AS uid, username
- T& p. z- h- `, f A1 K2 v5 j: A/ IFROM `post`
4 t2 K$ `0 L; u% k$ F) w. P; |" bLEFT JOIN post_user ON post.id = post_user.post_id
- X! v M5 N p( S, x3 E: ]7 qLEFT JOIN user ON user.id = post_user.user_id! S$ G- H3 ~; J* J
ORDER BY post_date DESC
% n" @4 o& L9 w! ^" |7 N它按预期工作。但是,我也希望获得每个帖子的评论数。因此,如何修改此查询,以便获得评论数。) i7 {1 V, c( l3 {3 t' T' w% ?
有任何想法吗?; s. T! Z( |& }) c, g! H
+ B7 T! K% V$ n# a4 O
解决方案:* E* F" b( Q+ [6 b6 t
5 i; v! f9 [2 s4 I5 v& u
0 ]& q; \! @; z9 f5 ^: L! y2 c' U- t( I' b7 E0 @
SELECT post.id, post.title, user.id AS uid, username, COALESCE(x.cnt,0) AS comment_count2 |9 Q& \$ M* Q' r5 p+ c
FROM post
8 x7 i6 O8 c6 O0 H: {3 ? LEFT JOIN post_user ON post.id = post_user.post_id
5 |* |+ J$ N- B) x" h3 @8 ]% _9 S LEFT JOIN user ON user.id = post_user.user_id
. M6 T) J2 d9 X$ o% G LEFT OUTER JOIN (SELECT post_id, count(*) cnt FROM post_comments GROUP BY post_id) x ON post.id = x.post_id
# ?8 d0 s* S0 E' t: Y- Q* U ORDER BY post_date DESC: h3 G5 ~) G m2 Y/ z! L
编辑:在没有任何评论的情况下使其成为外部联接
4 E: @3 c8 ]' [* E) s3 }EDIT2:更改IsNull为Coalesce |
|