简体   繁体   English

查询从 mysqli 表中提取数据

[英]Query to pull data from mysqli table

I created a database of users, posts and friends and want to pull all post from posts where account_name is $u = "logged in user" and also where account_name is ​"in the friends list of logged in user"我创建了一个用户、帖子和朋友的数据库,并希望从 account_name 是 $u = "logged in user" 并且 account_name 是“在登录用户的朋友列表中”的帖子中提取所有帖子

​How can i add the query to pull sth like that?我怎样才能添加查询来拉这样的东西? Please check query bellow:请检查以下查询:

 ​$sql = "SELECT p.*, u.avater FROM posts AS p 
    LEFT JOIN users AS u ON u.username = p.author 
    WHERE (p.account_name='$u') OR (p.account_name = '(if exist in logged_user friends list')  
    ORDER BY p.postdate DESC LIMIT 20";

One way to accomplish this would be to use IN and then select a subquery in your WHERE statement, see below.实现此目的的一种方法是使用IN ,然后在WHERE语句中选择一个子查询,见下文。

I'm not sure of your table structure in logged_user , but simply select one column ( id , in the example below) and then use the $u user in the WHERE statement.我不确定您在logged_user中的表结构,但只需选择一列( id ,在下面的示例中),然后在WHERE语句中使用$u用户。

Note, it's bad practice to include the '$u' directly in the query, and you should be using prepared statements.请注意,在查询中直接包含 '$u' 是不好的做法,您应该使用准备好的语句。

SELECT p.*, u.avater 
FROM posts AS p 
LEFT JOIN users AS u ON u.username = p.author
WHERE p.account_name = '$u'
OR p.account_name IN (SELECT user2 FROM friends WHERE user1 = '$u')
ORDER BY p.postdate DESC LIMIT 20

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

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