简体   繁体   English

MySQL查询涉及三个阶段和两个表

[英]MySQL query involving three stages and two tables

Database: 数据库:

  • xx_users (id, name, user_id, email, location) xx_users(id,name,user_id,email,location)
  • xx_questions (id, question, description, user_id) xx_questions(id,question,description,user_id)

Code: 码:

$friends = $facebook->api('/me/friends');
$arr= $friends['data'];
$friend_ids_arr = array();
foreach($arr as $friend) {
    $friend_ids_arr[] = $friend['id'];
}

$sql = "SELECT (SELECT * FROM xx_questions WHERE user_id IN (" . implode(',', $friend_ids_arr) . ") OR user_id = '$user' ORDER BY time DESC) (SELECT * from questions INNER JOIN users ON users.user_id = questions.user_id WHERE users.location = 'Cambridge, Cambridgeshire')";    
$data = mysql_query($sql) or die(mysql_error());

while ($row = mysql_fetch_assoc($data)) {
       // echo values from what's been selected
}

I am trying to select questions from xx_questions (that have been posted by users) should any of three situations arise: 如果出现以下三种情况,我试图从xx_questions (已由用户发布)中选择问题:

  1. Those values where the poster's user_id matches that of one of the current user's friends (ie the poster and the user are friends) 海报的user_id与当前用户的一个朋友(即海报和用户是朋友)的值匹配的那些值
  2. Those values where the poster's user_id matches that of the user (ie the poster is the user) 海报的user_id与用户的user_id匹配的那些值(即海报是用户)
  3. Those values where the poster's location matches that of the current user (ie the poster and user are currently in the same city) 海报的位置与当前用户的位置匹配的那些值(即海报和用户当前在同一个城市)

I have managed to make 1 and 2 work, but the problems arise when I try to introduce 3, so my two questions are: 我已经设法让1和2工作,但当我尝试引入3时出现问题,所以我的两个问题是:

  1. What is the correct MySQL for 3? 什么是3的正确MySQL?
  2. How is that integrated with 1 and 2? 如何与1和2集成?

Thanks in advance, let me know if you need more information. 在此先感谢您,如果您需要更多信息,请与我们联系。

To get the information that you want, you need to join xx_questions to xx_users. 要获取所需的信息,需要将xx_questions连接到xx_users。 Something like the following returns questions that match any one of the three conditions: 类似下面的内容会返回与以下三个条件中的任何一个匹配的问题:

select *
from xx_questions q join
     xx_users u
     on q.user_id = u.user_id
where q.user_id in (<implode(',', $friend_ids_arr)>) or
      q.user_id = '$user' or
      u.location = (select location from xx_users where USER_ID = $user)

I have written this more like SQL than as a string, so it is easier to read. 我把它写成SQL更像是一个字符串,所以它更容易阅读。

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

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