我在此查询中收到错误:
SELECT i.name, i.surname, (SELECT u.username FROM user u WHERE u.info_id IN (1,9,10,15,25,40,42,43,44)) as email FROM `userinfo` i WHERE i.id IN (1,9,10,15,25,40,42,43,44)
错误:
基数违规:1242子查询返回超过1行
我知道这可以通过使用JOIN语句来解决,但我不知道如何解决这个问题。
为了澄清我的问题,我有两个表,user和userinfo:
用户
id info_id username
USERINFO
id name surname
来自user
的info_id行与userinfo
的id相关,因此以这种格式(1,4,7,8,9)列出了用户信息ID我想要名字和姓氏(来自userinfo
)和来自user
的用户名与info_id
答案 0 :(得分:10)
您需要在相关子查询中指定两个表之间的关系
SELECT i.name,
i.surname,
(
SELECT u.username
FROM user u
WHERE u.info_id = i.id) as email
FROM userinfo i
WHERE i.id IN (1,9,10,15,25,40,42,43,44)
并使用JOIN
(我更喜欢)
SELECT i.name,
i.surname,
u.username as Email
FROM userinfo i
INNER JOIN user u
ON u.info_id = i.id
WHERE i.id IN (1,9,10,15,25,40,42,43,44)
要进一步了解联接,请访问以下链接:
答案 1 :(得分:2)
您只能在字段列表中返回一行。您似乎想要对结果进行分组。
SELECT
i.name, i.surname,
GROUP_CONCAT(u.username) AS email
FROM
userinfo i
JOIN user u ON (i.id = u.info_id)
WHERE
i.id IN (1,9,10,15,25,40,42,43,44)
GROUP BY
i.id
答案 2 :(得分:1)
SELECT i.name, i.surname, u.username as email
FROM `userinfo` i
INNER JOIN
`user` u ON i.info_id=u.id
WHERE i.id IN (1,9,10,15,25,40,42,43,44)
学会使用连接,没有它们,你的双手被绑在背后蒙住双眼。联接是如何使用关系数据库的关系部分。
答案 3 :(得分:0)
你的意思是:
SELECT i.name, i.surname, (SELECT u.username FROM user u WHERE u.id IN (1,9,10,15,25,40,42,43,44)) as email
FROM `userinfo` i
WHERE i.id IN (1,9,10,15,25,40,42,43,44)