dongzhan5246 2015-04-21 16:39
浏览 201
已采纳

从2个表中获取数据,其中一个表依赖于另一个表

Main Table: 'posts'.
Structure:

id || text || time || user_id


Secondary table: 'likes'.
Structure:

id || post_id || time || user_id


Here, the post_id from the 2nd table can (& must) be an ID from the 1st table. I want to run a query where I will fetch all IDs from the posts table of a specific user_id and also all POST_IDs from the likes table of a specific user_id.

This is what I tried but it only gets the IDs from the posts table, nothing from the likes table is fetched:

"SELECT id FROM posts WHERE id IN (SELECT post_id FROM likes WHERE user_id=$userid) OR id IN (SELECT id FROM posts WHERE user_id=$userid)"

However, when I remove the OR statement at the end, the post_ids from the likes table are fetched:

"SELECT id FROM posts WHERE id IN (SELECT post_id FROM likes WHERE user_id=$userid)"

What am I doing wrong? Please help. Much appreciated. Thanks!

Extra:

Any way to order them in ID's descending order?

If I order them by "p.id DESC" then all post_ids from likes table appear at the bottom.

For example,
there are 7 ids in post table (1, 2, 3, 4, 5, 9, 10),
3 in likes table (6, 7, 8).

Currently it displays like this: 10, 9, 5, 4, 3, 2, 1, 6, 7, 8.

How to display it like: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1? Thanks!

  • 写回答

2条回答 默认 最新

  • dongyata3336 2015-04-21 16:44
    关注

    You can try mysql LEFT JOIN on this scenario like this way if you want to get ALL id from post table, otherwise simple INNER JOIN will do your task.

    SELECT p.id,l.post_id FROM posts p 
       LEFT JOIN likes l ON p.id=l.post_id 
    WHERE p.user_id=$userid OR l.user_id=$userid
    

    Edit:

    SELECT p.id FROM posts p 
    LEFT JOIN likes l ON p.id=l.post_id 
    WHERE p.user_id=$userid OR   
    l.user_id=$userid
    ORDER BY p.id DESC
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 seata使用出现报错,其他服务找不到seata
  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误