简体   繁体   English

将子查询转换为连接查询

[英]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) 基数违规:1241操作数应包含1列

Would it be possible to use 2 columns in a join instead of a subquery? 是否可以在连接中使用2列而不是子查询? 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: 如果您希望user_id位于user_one或users_two的friends表中的users表中的记录,您可以执行以下操作:

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. 您的查询返回错误,因为IN子句无法在where语句中的多个列上进行选择。

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. IN操作数只接受一个参数。 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: 您可以使用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: 然后,将其用作IN参数:

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');

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

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