sql匹配另一个表中的id并连接

mwecs4sa  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(264)

中的id字段 article , tweetposts.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_idauthorcreated_at, modified_at....
1A...
2B...
3C...
4D...
5E...

## 文章
article_idtitle...
1A
3B

## 推特
tweet_idmessage...
2Hello World
slwdgvem

slwdgvem1#

如果我没弄错的话,你可能在找一个 LEFT JOIN 以及 coalesce() .

SELECT p.*,
       coalesce(a.article_id, t.tweet_id) article_id_or_tweet_id,
       coalesce(a.title, t.message) article_title_or_tweet_message
       FROM posts p
            LEFT JOIN article a
                      ON a.article_id = p.post_id
            LEFT JOIN tweet t
                      ON t.tweet_id = p.post_id
       WHERE p.post_id = ?;

(更换 ? 使用要查询的帖子的id。)

wvmv3b1j

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) 希望这对你有帮助。

6ss1mwsb

6ss1mwsb3#

您应该能够使用union,因为只有一个select将返回给定id的行

SELECT p.*, a.title as 'post'
FROM posts p
JOIN article a ON p.post_id = a.article_id
WHERE p.post_id = 2
UNION 
SELECT p.*, m.message as 'post'
FROM posts p
JOIN tweet t ON p.post_id = t.tweet_id
WHERE p.post_id = 2

相关问题