duanfangbunao36970 2013-03-08 15:09
浏览 17

多个WHERE查询

I am making a news feed page like in Facebook, Twitter, or any other social media sites out there.

My problem is I need to get all the user id's of each user's friends, then use all those values to query another table that has all the new updates.

So, let's say I have 3 friends (1,2,3). I want to search another table using all 3 values in my WHERE clause in the same query so that I can order it by date.

The way I've done it so far puts all the id's into an array and uses a foreach loop to query my db for every value I have, but this groups all the results based on the order of user id in the array, so my results come out like this 11111,222222,333333 instead of the time the update was made. So, even if 3 makes an update days before 1 or 2, it will always come after two.

I am aware this might not be the best way to do it, but so far it's the only method I can think of.

Please any assistance you could provide would be greatly appreciated.

My code:

$id = $_SESSION['id'];
$update = mysql_query("
    SELECT profile_id FROM `fiends` 
    WHERE `my_fiend_id` = '$id'
    ");
$result = $update;
$fiends = array();

while (($row = mysql_fetch_assoc($result)) !== false) {
    $fiends[] = array(
        'id' => $row['profile_id'],
);}

foreach($fiends as $fiend) {
    $fiend_id = $fiend['id'];
    $update_select = mysql_query("          
        SELECT * FROM `update` 
        WHERE `NU_id` = '$fiend_id'                 
        ORDER BY `time` DESC
        ");

$result = $update_select;
  • 写回答

2条回答 默认 最新

  • doudun3040 2013-03-08 15:11
    关注

    You should turn this into one query

    SELECT `update`.*
    FROM `update`
    INNER JOIN `fiends` ON update.`NU_id` = fiends.`my_fiend_id`
    WHERE `my_fiend_id` = '$id'              
    ORDER BY `time` DESC
    

    Alternatively, you can use an IN () statement

    "SELECT * FROM `update` WHERE `NU_id` = IN ('".join(',', $fiend_id)."')"
    

    Your final statement would look something like this

    WHERE `NU_id` IN (11111,222222,333333)
    

    If the NU_ID is a varchar column then make sure to use quotes around the values

    WHERE `NU_id` IN ('11111','222222','333333)
    
    评论

报告相同问题?

悬赏问题

  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私