中的id字段 article
, tweet
是 posts.post_id
.
在mysql中,我想以查询为例, post_id=2
.
如何从表中得到所需的结果 posts + tweet
(自 id=2
只存在于 tweet
表)
post_id | author | created_at .... | tweet_id | message | ... all cols from tweet
2 | B | ........... | 2 | Hello world | ...
查询时 post_id=1
,结果将从 posts + article
```
post_id | author | created_at.... | article_id | title | ... all cols from article
1 | A .............. | A | ...
谢谢你的帮助。
数据库摆弄:http://sqlfiddle.com/#!9/be4f302/21号
## 岗位
post_id | author | created_at, modified_at.... |
---|
1 | A | ... |
2 | B | ... |
3 | C | ... |
4 | D | ... |
5 | E | ... |
## 文章
## 推特
tweet_id | message | ... |
---|
2 | Hello World |
3条答案
按热度按时间slwdgvem1#
如果我没弄错的话,你可能在找一个
LEFT JOIN
以及coalesce()
.(更换
?
使用要查询的帖子的id。)wvmv3b1j2#
下面是一个可以尝试的查询。。
SELECT P.*, A.title, T.message FROM posts P LEFT JOIN article A ON (P.post_id = A.article_id) LEFT JOIN tweet T ON (T.tweet_id = P.post_id)
希望这对你有帮助。6ss1mwsb3#
您应该能够使用union,因为只有一个select将返回给定id的行