我的查询在哪里出错了?

时间:2013-01-09 11:14:44

标签: php mysql join

我在PHP / MySQL上相当不错,到目前为止已经成功了,但是,现在我需要从两个相关的表中获取信息。 我已经做了很多关于我需要做什么的研究,但似乎无法弄清楚我哪里出错了。

问题:如何从短链接表中获取与shortlink_analytics中的短链接相关的链接?

我收到错误:警告:mysql_fetch_array()期望参数1为资源,布尔值为

我的表格如下:

短链接表

ID

shortlink

链接

createdTime

createdBy

shortlink_analytics表

shortlink

引荐

hitTime

USERIP

userAgent

到目前为止我尝试过的代码是:

$linecount = 1;
//$mostPop is where I think I have gone wrong and this is where the warning refers to
$mostPop = "SELECT shortlink, COUNT(shortlink) FROM shortlink_analytics JOIN shortlinks ON shortlink_analytics.shortlink = shortlinks.shortlink GROUP BY shortlink ORDER BY COUNT(shortlink) DESC LIMIT 10";
            $loadPop = mysql_query($mostPop);
            echo '<table id="middleIndex">';
            echo '<tr><td class = "overFlow"><h2>Most Popular Shortlink</h2></td></tr>';
            echo '<tr>';
            while($row = mysql_fetch_array($loadPop))
            {
                    echo '<td class = "overFlow">'.$row[1].' visits - <a href = "info.php?link='. $row['shortlink'] .'">hud.ac/' . $row['shortlink'] . '</a></td>';
                    echo '</tr>';
                    $linecount++;
            }
            echo '<tr id="indexMiddle"><td id="hand" class = "overFlow"><a onclick="indexMostPopular()">View More</a></td></tr>';
                echo '</table>';

我相信我对如何使用 JOIN 或形成成功加入所需的参数缺乏足够的了解。

2 个答案:

答案 0 :(得分:1)

你在两个表中都有shortlink,这会产生不明确的情况。试试这个 sql语句

$mostPop = "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";

答案 1 :(得分:0)

试试这个(在mysql中运行此查询,如果它正在工作,请在php脚本中添加它)

SELECT 
    shortlink_analytics.shortlink, COUNT(shortlink_analytics.shortlink)
FROM
    shortlink_analytics
INNER JOIN
    shortlinks ON shortlink_analytics.shortlink = shortlinks.shortlink
GROUP BY shortlink_analytics.shortlink
ORDER BY COUNT(shortlink_analytics.shortlink) DESC
LIMIT 10

并检查mysql_effected_rows()函数以检查查询是否会返回某行