简体   繁体   English

结合使用MySQL选择查询和子查询

[英]Using a MySQL select query with a sub query

I am trying to select rows of data from a table where user_id does not equal the uder_id of the user logged in and where the user_id is not in the sub query. 我试图从其中user_id不等于已登录用户的uder_id且user_id不在子查询中的表中选择数据行。 For some reason I can't get it to work. 由于某种原因,我无法使其正常工作。 What could I doing wrong? 我该怎么办?

My Code: 我的代码:

SELECT * 
FROM table_name 
WHERE user_id != '".$_SESSION['id']."' 
    AND user_id NOT IN(
      SELECT * FROM another_table_name where user1= '".$user_id."' AND status= 1)
ORDER BY RAND()
LIMIT 5

You have to select only the user_id from another_table_name . 您只需要从another_table_name选择user_id Without seeing your table structure i am not able to help you further. 没有看到您的表结构,我无法进一步帮助您。

Your logic is correct. 您的逻辑是正确的。 What we don't know are the parameterized values in the query. 我们不知道查询中的参数化值。 My guess is those are not equal to the values you are expecting. 我的猜测是那些不等于您期望的值。

In your sub query you just want to select user_ids , you have your sub query using a "select *" 在您的子查询中,您只想选择user_ids,您的子查询使用“ select *”

SELECT * FROM table_name WHERE user_id != '".{$_SESSION['id']}."' AND user_id NOT IN(SELECT    
user_id FROM another_table_name where user1= '".$user_id."' AND status= 1) ORDER BY RAND()     LIMIT   5

You'll need to only select the user_id s from the sub query. 您只需要从子查询中选择user_id Maybe something like: 也许像:

SELECT * 
  FROM table_name 
  WHERE user_id != '".{$_SESSION['id']}."' 
    AND user_id NOT IN(SELECT user_id 
      FROM another_table_name 
      WHERE user1= '".$user_id."' 
      AND status= 1) 
  ORDER BY RAND() 
  LIMIT 5

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

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