Sql在另一个表中匹配id并加入

问题描述 投票:0回答:3

articletweet中的Id字段是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

posts

| post_id | author | created_at, modified_at....
|---------|--------|-----------
| 1       | A      | ...
| 2       | B      | ...
| 3       | C      | ...
| 4       | D      | ...
| 5       | E      | ...

article

| article_id | title | ...
|------------|-------|----
| 1          | A     | 
| 3          | B     | 

tweet

| tweet_id | message     | ...
|----------|-------------|---
| 2        | Hello World | 
mysql sql
3个回答
0
投票

这是一个你可以尝试的查询..

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)

希望这能帮到你。


0
投票

如果我理解这一点,你可能会追随LEFT JOINcoalesce()

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。)


0
投票

您应该能够使用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   
© www.soinside.com 2019 - 2024. All rights reserved.