简体   繁体   English

根据其他查询中的值选择查询

[英]Select query based on values from other query

Im not an expert in php, and i looked for something like this, but couldnt find anything (don't know exactly how to search for this, or what the name is). 我不是php方面的专家,我正在寻找类似的东西,但找不到任何东西(不确切地知道如何搜索它,或者名字叫什么)。

Case: 案件:

I have two seperate tables: 我有两个单独的表:

"friends": “朋友”:

id | id | friend_id | friend_id | foe_id foe_id

"updates": “更新”:

id | id | user_id 用户身份

And this code: 这段代码:

 $selectFriends = "SELECT * FROM friends WHERE friend_id = '".$_COOKIE['id']."' OR foe_id = '".$_COOKIE['id']."'";
$queryFriends = mysql_query($selectFriends)or die(mysql_error());

while($listFriends = mysql_fetch_assoc($queryFriends))
{
    echo "".$listFriends['friend_id']."";
    echo "".$listFriends['foe_id']."";

    $selectUpdates = "SELECT * FROM updates WHERE user_id != ".$_COOKIE['id']." AND user_id IN (' . implode(',', ".$listFriends['friend_id'].") . ') ORDER BY date DESC LIMIT 10";
    $queryUpdates = mysql_query($selectUpdates)or die(mysql_error());
}

I get the right id's that i want in the first query, but now i want to use the id's from the first query in the 2nd query; 我在第一个查询中得到了想要的正确ID,但是现在我想在第二个查询中使用第一个查询中的ID。 to select the updates of my "friends". 选择我的“朋友”的更新。 So in short: link the "friend_id" & "foe_id" to the "user_id" from the 2nd table. 简而言之:从第二个表中将“ friend_id”和“ foe_id”链接到“ user_id”。

Use sub-query, as the question is not that clear I am providing the idea only 使用子查询,因为问题不是很清楚,我只是提供这个想法

SELECT * FROM updates WHERE user_id IN (SELECT friend_id FROM friends WHERE friend_id = '".$_COOKIE['id']."' OR foe_id = '".$_COOKIE['id']."'");

Else you need to do little in PHP. 否则,您几乎不需要使用PHP。 Take all friend_id and foe_id records, prepare a comma separated string in a variable ($var). 记录所有friend_id和foe_id记录,并在变量($ var)中准备一个用逗号分隔的字符串 Use that in the query 在查询中使用

SELECT * FROM updates WHERE user_id IN ($var);

you may like to use GROUP_CONCAT as well 您可能也想使用GROUP_CONCAT

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

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