2015-12-02 51 views
0

雖然我不是全新的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 - 子查詢返回多個1行,我明白,誤差應該在那裏,我的問題是如何格式化代碼,以便它可以接受多個子查詢)

回答

0

中使用,而不是=

select distinct * from oglasi where id IN (select distinct ... 
             ^^ 
+0

非常感謝。 – alps

+1

不客氣,接受(點擊綠色複選標記)最能幫助你的答案是在這裏說謝謝的最好方式:) – Roberto

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,這也相當整齊。

+0

再一次,非常感謝您的意見。 – alps

0

使用INNER JOIN代替:

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 
+0

感謝您的輸入,我會研究內部連接,顯然在等於是解決了這個問題。 – alps

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; 
0

的子查詢被允許超過10行返回更多的時候你用 「IN」 或 「ANY」

我覺得您的查詢應該是:

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更好。

希望這會有所幫助。

相關問題