[英]Get data from 2 tables where one table is dependent of the other
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. 在这里,第二个表中的post_id可以(&必须)是第一个表中的ID。 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.
我想运行一个查询,从特定的user_id的posts表中获取所有ID,并从特定的user_id的likes表中获取所有POST_ID。
This is what I tried but it only gets the IDs from the posts table, nothing from the likes table is fetched: 这是我尝试过的方法,但它仅从posts表中获取ID,而从likes表中未获取任何内容:
"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: 但是,当我最后删除OR语句时,会从likes表中获取post_id:
"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? 有什么办法以ID的降序对其进行排序?
If I order them by "p.id DESC" then all post_ids from likes table appear at the bottom. 如果我通过“ p.id DESC”对它们进行排序,那么来自点赞表的所有post_id都会显示在底部。
For example, 例如,
there are 7 ids in post table (1, 2, 3, 4, 5, 9, 10), 帖子表中有7个ID(1、2、3、4、5、9、10),
3 in likes table (6, 7, 8). 点赞表中的3个(6、7、8)。
Currently it displays like this: 10, 9, 5, 4, 3, 2, 1, 6, 7, 8. 当前它显示如下: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? 怎样显示:10、9、8、7、6、5、4、3、2、1? Thanks!
谢谢!
Use a JOIN 使用加入
SELECT id FROM posts
LEFT JOIN likes ON posts.id = likes.post_id
WHERE likes.user_id = $userid
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. 如果您想从发布表中获取
ALL
ID,可以在这种情况下尝试mysql LEFT JOIN
,否则,简单的INNER JOIN
将完成您的任务。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.