子查询返回总是单个记录

时间:2015-12-11 05:59:29

标签: mysql

我尝试合并查询1是查询2的子查询3.但它将返回始终单个记录。 以下是我的查询,

import csv
dataFile = open('names.csv','rb')
reader = csv.reader(dataFile)
next(reader, None)
for row in reader: 
    if (row in reader ) 
        print (row[0])

示例代码,

1.SELECT REPLACE(LEFT(friend_id, LENGTH(friend_id)-2),'["','') AS friend_id FROM `friends_list` WHERE login_userid=90 

Output :
friend_id   
32,44

2.SELECT id, CONCAT(firstname," ",lastname) AS username FROM register WHERE id IN(32,44)

Output :
id  username    
32  Suresh M
44  Senthil Kumar

我想要结果,

3.SELECT t1.id, CONCAT(t1.firstname," ",t1.lastname) AS username 
FROM register AS t1 
INNER JOIN friends_list AS t2 ON t1.id=t2.login_userid
WHERE t1.id IN( SELECT REPLACE(LEFT(friend_id, LENGTH(friend_id)-2),'["','') AS friend_id FROM `friends_list` WHERE login_userid=90 )

Output :
id  username    
32  Suresh M

请纠正我的错误查询(第3次)。

4 个答案:

答案 0 :(得分:2)

SELECT id, CONCAT(firstname," ",lastname) AS username 
FROM register 
WHERE id IN( SELECT (select TRIM(BOTH '["' from (select TRIM(BOTH '"]' from friend_id)))) as friend_id  FROM `friends_list` WHERE login_userid=90 )     

答案 1 :(得分:2)

只需删除内部联接条件

SELECT t1.id, CONCAT(t1.firstname," ",t1.lastname) AS username 
    FROM register AS t1 
    WHERE t1.id IN( SELECT REPLACE(LEFT(friend_id,      LENGTH(friend_id)-2),'["','') AS friend_id FROM `friends_list` WHERE login_userid=90 )

答案 2 :(得分:1)

这应该对你有用@RamaLingam

不使用INNER JOIN,

尝试此操作
SELECT t1.id
    , CONCAT(t1.firstname, " ", t1.lastname) AS username
    FROM register t1
    WHERE t1.id IN (
        SELECT CAST(REPLACE(LEFT(t2.friend_id, LENGTH(t2.friend_id)-2),'["','') AS UNSIGNED)
            FROM friend_list t2
            WHERE t2.login_userid = 90
    )

答案 3 :(得分:-1)

你能试试这个:

SELECT R.id
    , CONCAT(R.firstname, " ", R.lastname) AS username
    FROM register R
    WHERE R.id IN (
        SELECT CAST(REPLACE(LEFT(F.friend_id, LENGTH(F.friend_id)-2) ,'["' ,'') AS UNSIGNED)
            FROM friend_list F
            WHERE F.login_userid = 90
    )