2013-05-30 53 views
0

這可能已被問到,但由於我是一個龐大的PHP/MySQL noob,我真的不知道它是什麼,我正在尋找。我執行以下查詢:PHP/MySQL子查詢返回多於一行

SELECT shortlink_analytics.shortlink AS short, 
COUNT(shortlink_analytics.shortlink) AS shortcount, 
(SELECT link FROM shortlinks WHERE shortlinks.shortlink = shortlink_analytics.shortlink) AS shLink 
FROM shortlink_analytics JOIN shortlinks ON shortlink_analytics.shortlink = shortlinks.shortlink 
GROUP BY shortlink_analytics.shortlink 
ORDER BY COUNT(shortlink_analytics.shortlink) DESC LIMIT 10 

這用來工作,但在上週已經重新審視它,我注意到輸出,而不是工作,顯示的錯誤:

Subquery returns more than 1 row 

後與我設法找到了問題所在(!我想)在該地區的代碼玩弄(但我不是很確定):

GROUP BY shortlink_analytics.shortlink 
ORDER BY COUNT(shortlink_analytics.shortlink) DESC LIMIT 10 

會有人能夠解釋:

  • 我哪裏出錯了?
  • 可能的原因,爲什麼它一個月工作,然後停止工作?
  • 什麼是解決我的問題的方法?
+0

爲什麼不使用'INNER JOIN'更換這部分'SELECT FROM shortlinks WHERE shortlinks.shortlink = shortlink_analytics.shortlink'鏈接。這使您的查詢更具可讀性,並可能表現更好... –

回答

3

這部分是子查詢:

(SELECT link FROM shortlinks WHERE shortlinks.shortlink = shortlink_analytics.shortlink)

你能簡單地LIMIT它1行?

(SELECT link FROM shortlinks WHERE shortlinks.shortlink = shortlink_analytics.shortlink LIMIT 1)

你應該嘗試找出爲什麼你的數據返回多個行,你甚至可能需要ORDER BY以確保返回正確的行。

+0

乾杯,這解決了我的問題。但是,你能否進一步擴展爲什麼這個工作會在幾個星期前工作,但隨後停止? –

+3

@SamStreet。 。 。因爲現在已經出現了數據更改和重複的情況。 –

1

如果你想獲得對關係的所有鏈接,使用group_concat()

SELECT shortlink_analytics.shortlink AS short, 
     COUNT(shortlink_analytics.shortlink) AS shortcount, 
     group_concat(link) as shlinks 
FROM shortlink_analytics JOIN 
    shortlinks ON 
    shortlink_analytics.shortlink = shortlinks.shortlink 
GROUP BY shortlink_analytics.shortlink 
ORDER BY COUNT(shortlink_analytics.shortlink) 
DESC LIMIT 10; 

如果這個猜測是錯誤的,你需要的子查詢,您仍然可以通過執行在group_concat()得到的所有鏈接子查詢:

SELECT shortlink_analytics.shortlink AS short, 
     COUNT(shortlink_analytics.shortlink) AS shortcount, 
     (SELECT group_concat(link) 
     FROM shortlinks 
     WHERE shortlinks.shortlink = shortlink_analytics.shortlink 
     ) AS shLinks 
FROM shortlink_analytics JOIN 
    shortlinks 
    ON shortlink_analytics.shortlink = shortlinks.shortlink 
GROUP BY shortlink_analytics.shortlink 
ORDER BY COUNT(shortlink_analytics.shortlink) DESC 
LIMIT 10