MySQL子查询返回多行,如何解决?

时间:2015-12-02 21:46:20

标签: mysql

虽然我并不是全新的MySQL并且我已经掌握了基础知识,但我正在努力学习以下代码,其子查询返回多行 - 这应该是。我的问题是你如何让它与多行一起工作,从视角来看,子查询有多个结果,我得从每个结果中得到结果。

select distinct * from oglasi where id = (select distinct zanimanja_oglasi.id_o from zanimanja_oglasi, zanimanja_uporabniki where zanimanja_oglasi.id_z = zanimanja_uporabniki.id_z and zanimanja_uporabniki.id_u = 3) order by id desc limit 50

(对于下面的我得到了上面提到的错误,#1242 - Subquery返回超过1行,我确实理解错误应该存在,我的问题是如何格式化代码以便它可以接受多个子查询)

5 个答案:

答案 0 :(得分:0)

使用in关键字,如下所示:

select distinct * 
from oglasi 
where id IN (
  select distinct zanimanja_oglasi.id_o 
  from zanimanja_oglasi 
  inner join zanimanja_uporabniki 
    on zanimanja_oglasi.id_z = zanimanja_uporabniki.id_z 
    and zanimanja_uporabniki.id_u = 3
) 
order by id desc limit 50

您也可以试用where exists个关键字:

select distinct * 
from oglasi o
where exists (
  select 1
  from zanimanja_oglasi 
  inner join zanimanja_uporabniki 
    on zanimanja_oglasi.id_z = zanimanja_uporabniki.id_z 
    and zanimanja_uporabniki.id_u = 3
  where zanimanja_oglasi.id_o = o.id
) 
order by id desc limit 50

Giorgos提到了使用inner join,这也非常简洁。

答案 1 :(得分:0)

改为使用echo basename(dirname($image));

INNER JOIN

答案 2 :(得分:0)

使用IN而不是=

select distinct * 
from oglasi as t1
inner join (
   select distinct zanimanja_oglasi.id_o as id
   from zanimanja_oglasi, zanimanja_uporabniki 
   where zanimanja_oglasi.id_z = zanimanja_uporabniki.id_z and 
         zanimanja_uporabniki.id_u = 3 
) AS t2 on t1.id = t2.id
order by t1.id desc limit 50

答案 3 :(得分:0)

检查一下。

 select distinct oglasi.* from oglasi
 inner join zanimanja_oglasi on (zanimanja_oglasi.id_o=oglasi.id)
 inner join on (zanimanja_oglasi.id_z = zanimanja_uporabniki.id_z)
 where zanimanja_uporabniki.id_u = 3
order by oglasi.id desc limit 50;

答案 4 :(得分:0)

当您使用“IN”或“ANY”时,子查询允许返回超过1行

我认为你的查询应该是:

SELECT DISTINCT *
    FROM oglasi
    WHERE id IN (SELECT DISTINCT zanimanja_oglasi.id_o
        FROM zanimanja_oglasi, zanimanja_uporabniki
        WHERE zanimanja_oglasi.id_z = zanimanja_uporabniki.id_z
        AND zanimanja_uporabniki.id_u = 3)
        ORDER BY id DESC LIMIT 50

或者

SELECT DISTINCT *
    FROM oglasi
    WHERE id = ANY (SELECT DISTINCT zanimanja_oglasi.id_o
        FROM zanimanja_oglasi, zanimanja_uporabniki
        WHERE zanimanja_oglasi.id_z = zanimanja_uporabniki.id_z
        AND zanimanja_uporabniki.id_u = 3)
        ORDER BY id DESC LIMIT 50

恕我直言,最好使用IN。

希望这有帮助。