简体   繁体   中英

Choose to Select Value Between Two Columns in MySQL

Just working on a personal project. I am trying to write an SQL query ( using PHP and MYSQL ) that selects the appropriate row from a table based on some condition.

I've done a bit of research and have been fiddling with it for a few days but no luck.

So, I have a table called Friendship_Request. Although the table has several columns, one of them is called Requester_ID and another column is called Requestee_ID . If one of the columns matches a value I pass in the query (say, userID ) then I want the query to bring me back the value in the other column. For example,

在此处输入图片说明

If I pass 200 as the userID then the query should bring back 201, 400 and 901. How do you do this? Does this have a name? I didn't even know what to Google.

Thanks for your time.

SELECT if(Requester_ID=200, Requestee_ID, Requester_ID) as friendid FROM Friendship_Request WHERE Requester_ID = 200 OR Requestee_ID=200;

希望此查询能解决您的问题。

在此处输入图片说明 First we fetch all the Requester_ID and Requestee_ID with values equal to userID. Then we select the Requestee_ID if the Requester_ID == userID and select Requester_ID if the Requester_ID != userID.

SELECT IF( Requester_ID = 200, Requestee_ID, Requester_ID ) AS Request
FROM Requester
WHERE Requester_ID = 200 OR Requestee_ID = 200

Output :

Request

201

400

901

One option is to use a UNION :

SELECT Requester_ID AS ID
  FROM Friendship_Request
 WHERE Requestee_ID = 200
 UNION
SELECT Requestee_ID
  FROM Friendship_Request
 WHERE Requester_ID = 200;

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