简体   繁体   中英

How to get record from a table with dynamic condition in mysql

i am having a table tb_user in which the records are as:

id   Name    Gender   Age
1    Arun     Male    23
2    Neha    Female   22
3   Sheetal  Female   21
4    Vikas    Male    20

what i need to do is if i get the id = 1 from the api then i need to to fetch the record which are apposite in gender.what i am doing is first fetching the gender of that id then putting the condition as follows:

Select Gender from tb_user where id = 1;

then another query to get the record for that id

Select * from tb_user where Gender != $gender;

$gender is the gender which we got from the previous query.

what is need to do is to complete this task in a single query.

您可以使用subQuery实现您的目标。

SELECT * FROM tb_user WHERE Gender <> (SELECT Gender FROM tb_user WHERE id = 1);

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