0

这可能已经被问过了,但由于我是一个庞大的 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

谁能解释一下:

  • 我哪里出错了?
  • 为什么它工作一个月然后停止工作的可能原因是什么?
  • 解决我的问题的方法是什么?
4

2 回答 2

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确保返回正确的行。

于 2013-05-30T13:20:57.103 回答
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
于 2013-05-30T13:24:40.920 回答