将子查询转换为连接查询

时间:2015-02-24 18:04:29

标签: mysql sql

对于此查询:

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

我收到此错误消息:

  

基数违规:1241操作数应包含1列

是否可以在连接中使用2列而不是子查询?如果是的话,怎么样?

7 个答案:

答案 0 :(得分:2)

为什么不使用这样的联盟:

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

答案 1 :(得分:1)

如果您需要users表中user_id位于friends表的user_one或user_two中的记录,您可以执行以下操作:

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

答案 2 :(得分:0)

选择a.userid,a.username 来自用户a 内心加入朋友b 在a.userid = b.userid上 其中b.user_one =' $ my_id'或者b.user_two =' $ my_id'

答案 3 :(得分:0)

试试这个:

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'

答案 4 :(得分:0)

您的查询返回错误,因为IN子句无法在where语句中选择多个列。

我认为你在寻找的东西可能是这样的

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

答案 5 :(得分:0)

SELECT user_id,user_name 来自用户a,朋友b WHERE a.user_id = b.user_one AND(b.user_one =' $ my_id'或者b.user_two =' $ my_id')

答案 6 :(得分:0)

IN操作数只接受一个参数。如果你想得到你所有的朋友,你需要以只返回一列的方式这样做。您可以使用UNION执行类似的操作:

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

然后,将其用作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');