我有这个问题:
select a.*, b.*, (select c.* from tableC c where c.id_tableA = a.id) from tableA a inner join tableB b on a.id = b.id_tableA where b.id_user = 50;
子查询(即tableC)按预期返回超过1行。如何从tableC返回1行,以便它可以与查询的其余部分匹配?
到目前为止,我已经尝试过这个:
(select c.* from tableC c where c.id_tableA = a.id limit 1)
它不起作用,因为mysql说:
“操作数应包含1列”
答案 0 :(得分:0)
你混合了两件事。 SELECT
列表中的标量子查询应该只返回一个值(行和列)。使用LIMIT 1
将获得一行,但仍然有很多列。
所以你可以指定列名:
select a.*, b.*,
(select c.col_name from tableC c where c.id_tableA = a.id order by .. limit 1)
from tableA a
inner join tableB b on a.id = b.id_tableA
where b.id_user = 50;
或使用普通JOIN
:
select a.*, b.*, c.*
from tableA a
inner join tableB b
on a.id = b.id_tableA
left join tableC c
on c.id_tableA = a.id
where b.id_user = 50;
答案 1 :(得分:0)
如果表C中的列id是主键,那么它应该没有问题 但如果不是,请尝试添加另一个条件来过滤子查询结果,如
例如这里是start_date:
SELECT a.column_1, b.column_2,
(SELECT column_3 FROM tableC
WHERE (id = a.id
AND (start_date = (SELECT MAX(b.start_date)
from tableC as c
where a.id = c.id ))) AS column_3
FROM tableA as a INNER JOIN
tableB as b ON b.id = a.id
WHERE b.id_user = 50;