我有两张桌子:
users
:
friends
:
我希望每个用户都能看到他们的朋友和朋友请求。我有显示朋友用户名的问题。我使它工作,但这是一个糟糕的解决方案,我想只使用一个查询(如果可能)解决这个问题。
我试过了:
$sql = "SELECT friends.friend_id, friends.user_id, users.user_name FROM friends
INNER JOIN users ON friends.user_id = users.user_id
WHERE friends.user_id = " . $_SESSION['user_id'] . " AND confirmed = 1
OR friends.friend_id = " . $_SESSION['user_id'] . " AND confirmed = 1;";
我的问题是它会在好友表中显示user_name
与user_id
相同的user_id
用户。我的查询需要检查user_id
是否与$_SESSION['user_id']
相同,如果相同则必须返回user_name
与user_id
相同的用户friend_id
friends
表格中的string date_time = "2018-04-24 10:00:00";
string[] words = date_time.Split(' ');//Split string
string date = words[0];//date = 1st object (before space)
string time = words[1];//time= 2nd object (after space)
。
答案 0 :(得分:0)
以下列方式制定您的SQL查询,
$sql = "SELECT
" . $_SESSION['user_id'] . " as user_id,
IF(u2.user_id = " . $_SESSION['user_id'] . ", u1.user_id, f.friend_id) as friend_id,
IF(f.user_id = " . $_SESSION['user_id'] . ", u2.user_name, u1.user_name) as friend_username
FROM users as u1
INNER JOIN friends as f
ON u1.user_id = f.user_id
INNER JOIN users as u2
ON f.friend_id = u2.user_id
WHERE (f.user_id = " . $_SESSION['user_id'] . " OR f.friend_id = " . $_SESSION['user_id'] . ") AND f.confirmed = 1";
这是现场演示: http://sqlfiddle.com/#!9/e10252/7
旁注:了解prepared statement因为您的查询现在容易受到SQL注入攻击。另请参阅how you can prevent SQL injection in PHP。