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

报告相同问题?

悬赏问题

  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则