简体   繁体   English

SQL在另一个表中匹配ID并加入

[英]Sql match id in another table and join

Id fields in article , tweet are foreign keys to the posts.post_id . articletweet中的id字段是posts.post_id外键。

In MySQL, I would like to query for example, post_id=2 . 在MySQL中,我想查询例如post_id=2

How do i get the desired result from table posts + tweet (since id=2 only exists in tweet table) 我如何从表格posts + tweet获得所需的结果(因为id=2仅存在于tweet表中)

post_id | author | created_at .... | tweet_id | message     | ... all cols from tweet
2       | B      | ...........     | 2        | Hello world | ...

When query post_id=1 , result will be col from posts + article 当查询post_id=1 ,结果将为posts + article col

post_id | author | created_at.... | article_id | title | ... all cols from article
1       | A             ..............         | A     | ...

Thanks for helping. 感谢您的帮助。


Database fiddle: http://sqlfiddle.com/#!9/be4f302/21 数据库小提琴: 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 | 

If I understand this right, you might be after a LEFT JOIN and coalesce() . 如果我理解这项权利,那么您可能在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 = ?;

(Replace the ? with the ID of the post you want to query.) (将?替换为您要查询的帖子的ID。)

Here is a query that you can try out.. 这是一个您可以尝试的查询。

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)

Hope this helped you. 希望这对您有所帮助。

You should be able to use UNION since only one of the SELECT will return a row for a given id 您应该能够使用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   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM