简体   繁体   English

MySQL循环或嵌套查询

[英]MySQL loop or nested query

Say I have a table friends 说我有一个餐桌朋友

user_1  |  user_2  

Then, say I want to see what these friends have been up to, so I check the posts table and updates table 然后,说我想看看这些朋友做了什么,所以我检查了posts表和updates表

post_id  | post_title | post_message |  user_id | timestamp

update_id | title | userid | timestamp

I want to achieve logic like the following : Get list of friends, go through this list of generated friends to see if they have added anything, sorted by the most recent activities first (timestamp). 我想实现如下逻辑:获取朋友列表,遍历生成的朋友列表,看看他们是否添加了任何东西,并按最近的活动(时间戳)进行排序。

Select user_1 from friends where user_2 = '$my_userid'
union
Select user_2 from friends where user_1 = '$my_userid'

//now loop through each of these friends and check the update/post tables to see if they have added anything recently

Can I do this all through 1 MySQL query, or do I have to break it up and use PHP? 我可以通过1个MySQL查询完成所有操作,还是必须将其分解并使用PHP?

post_id | post_id | post_title | post_title | post_message | post_message | user_id | user_id | timestamp - Table_A 时间戳-Table_A

update_id | update_id | title | 标题| userid | 用户名| timestamp - Table_B 时间戳-Table_B

Try the below query 试试下面的查询

SELECT A.*, B.* FROM Table_A AS A JOIN Table_B AS B ON B.userid = A.user_id
WHERE A.user_id IN (100,101,102) 
ORDER BY B.timestamp DESC;

A.* - will get you all the columns from the table A. If you want specific column A.post_id . A. *-将获得表A中的所有列。如果需要特定的列A.post_id

You can number of results by adding a LIMIT clause. 您可以通过添加LIMIT子句来获得多个结果。

Note : I assume 100,101,102 are the user ids generated. 注意:我假设100,101,102是生成的用户ID。 You can add the user ids within the IN Clause. 您可以在IN子句中添加用户ID。

Update 更新资料

Put the user ids you need in the IN clause if you want to limit the friends. 如果您想限制好友,请将您需要的用户ID放在IN子句中。 if not remove the where clause, so you can get the updates of all the friends without a limitation. 如果不删除where子句,则可以不受限制地获取所有朋友的更新。 You can order by any column you need. 您可以按需要的任何列进行订购。 You can do ORDER BY A.user_id , A.post_id, Even multiple columns are possible 您可以执行ORDER BY A.user_id,A.post_id,甚至可能有多列

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

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