从一个表中收集值并在第二个查询中使用它?

时间:2016-01-06 19:49:43

标签: php sql

好的,这听起来很愚蠢,但在最好的方法上遇到一些困难;我试图抓住帐户关注的所有用户;然后,一旦我抓住了下表中的所有用户,就抓住users表的用户信息。这就是我到目前为止所做的一切,但它真的很乱,不起作用。

<?
$usr_id = '34';

$sql = "SELECT * FROM following WHERE usr_id = '$usr_id'";
$result = mysql_query($sql);
// $following is the users that we are following.
while ($row = mysql_fetch_assoc($result)) {

        $following = $row['following'];

$src = "SELECT * FROM usr_users WHERE username = '$following'";
$getfollowinginfo = mysql_query($src);

while ($user = mysql_fetch_assoc($getfollowinginfo)) { 

        echo $user['email'];

}}
?>

1 个答案:

答案 0 :(得分:0)

正如其他人所说,public class HistoClass { public string date; [JsonProperty(NullValueHandling=NullValueHandling.Ignore)] public int? value1; [JsonProperty(NullValueHandling=NullValueHandling.Ignore)] public int? value2; } ... List <Models.HistoClass> HistoData= new List<Models.HistoClass>(); HistoData.Add(new Models.HistoClass {date="bla",value1="bla1",value2="bla3"}); HistoData.Add(new Models.HistoClass { date= "blx", value2="blax2" }); 在这里更合适。根据您的示例,here is a simple SQL Fiddle显示其工作原理。

最重要的部分是将JOIN表格然后Following定位到JOIN表格,如下所示:

Users

对于小型或简单数据集,这非常好,但有些人可能会建议您删除SELECT u.id, u.name FROM Following f JOIN Users u on u.id=f.following WHERE f.userId = 3 -- Can be any identifier for the user. 子句,而是扩展JOIN条件,如下所示:

WHERE

要将其集成到您的代码中,它就像这样简单;

SELECT u.id, u.name
FROM Following f
JOIN Users u on u.id=f.following
    AND f.userId = 3 -- Can be any identifier for the user.