简体   繁体   中英

Turn subquery into join query

For this query:

SELECT `user_id`, `user_name` FROM users WHERE `user_id` IN (SELECT user_one, user_two FROM friends WHERE user_one='$my_id' OR user_two = '$my_id')

I get this error message:

Cardinality violation: 1241 Operand should contain 1 column(s)

Would it be possible to use 2 columns in a join instead of a subquery? And if yes, how?

Why not use a union like this:

SELECT `user_id`, `user_name` 
        FROM users 
           WHERE `user_id` IN (SELECT user_one FROM friends 
                                               where user_one = '$my_id'
                               UNION
                               SELECT user_two FROM friends 
                                               where user_two = '$my_id')

If you want records from the users table where your user_id is in user_one or user_two of the friends table, you can do the following:

SELECT `user_id`, `user_name` 
FROM users 
WHERE `user_id` IN (
    SELECT user_one 
    FROM friends 
    WHERE user_one = '$my_id'
)
UNION ALL
SELECT `user_id`, `user_name` 
FROM users 
WHERE `user_id` IN (
    SELECT user_two 
    FROM friends 
    WHERE user_two = '$my_id'
);

从用户选择a.userid,a.username a.userid = b.userid中的内部联接朋友b,其中b.user_one ='$ my_id'或b.user_two ='$ my_id'

try this:

SELECT user_id, user_name FROM users U
join friends F
ON F.user_id=U.user_id
and F.user_name=U.user_name
WHERE  F.user_one='$my_id' OR F.user_two = '$my_id'

Your query returns the error because an IN clause cannot select on more than one column in a where statement.

I think what you are looking for may be something like this

SELECT 
    user_id, 
    user_name 
FROM users INNER JOIN Friends ON Users.User_ID = User_one OR Users.User_ID = User_Two

SELECT user_id,user_name FROM users a,friends b WHERE a.user_id = b.user_one AND(b.user_one ='$ my_id'OR b.user_two ='$ my_id')

The IN operand only takes one parameter. If you want to get all of the people you are friends with, you need to do so in a way that only returns one column. You can do something like that with a UNION:

SELECT user_one
FROM friends
WHERE user_two = 'me'
UNION
SELECT user_two
FROM friends
WHERE user_one = 'me';

Then, use that as your IN parameter:

SELECT user_id, user_name
FROM users
WHERE user_id IN(
   SELECT user_one
   FROM friends
   WHERE user_two = 'me'
   UNION
   SELECT user_two
   FROM friends
   WHERE user_one = 'me');

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