简体   繁体   中英

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. 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 . 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 *"

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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