无法计算联接表mySQL的结果

时间:2016-06-05 00:41:17

标签: mysql

我跟随其他3个SO答案,他们说它有效......但是这里没有......这是我的问题,我有这个QUERY:

var animate_menu_profiles = function(i) {
    var $profileContainer = $(".profile-container");
    var $profiles = $(".profiles");
    $profiles.sort(function(a,b) { return Math.random()-0.5; });
    $profiles.each(function(i){
        $(this)
          .toggleClass("transition-" + i)
          .appendTo($profileContainer);
    });

    build_menu_profiles();
};

这是查询的结果: Query Result

直到这里,它是完美的..现在我需要知道返回多少行...我将查询更改为:

SELECT
    q.*
FROM relacionamento AS r
INNER JOIN questoes AS q ON r.idquestao = q.id
WHERE tabela = 'disciplina'
GROUP BY q.id

得到了这个错误:

Error when counting

为什么我无法计算我得到了多少行?

更新 我也尝试过这个查询:

SELECT
    COUNT(q.*)
FROM relacionamento AS r
INNER JOIN questoes AS q ON r.idquestao = q.id
WHERE tabela = 'disciplina'
GROUP BY q.id

得到这个结果:

Count(*)Result

2 个答案:

答案 0 :(得分:2)

您可以这样更改:

SELECT COUNT(*) FROM (
    SELECT
        q.*
    FROM relacionamento AS r
    INNER JOIN questoes AS q ON r.idquestao = q.id
    WHERE tabela = 'disciplina'
    GROUP BY q.id
)

答案 1 :(得分:1)

您的查询可能写得更好:

SELECT q.*
FROM questoes q
WHERE EXISTS (SELECT 1
              FROM relacionamento r
              WHERE r.idquestao = q.id AND r.tabela = 'disciplina'
             );

如果您在relacionamento(idquestao, tablea)上有一个索引(对join无论如何),这应该比您的查询更有效率。并且,它不会将select *group by一起使用,这通常看起来不对。

然后,为了得到计数,你可以count(*)

SELECT COUNT(*)
FROM questoes q
WHERE EXISTS (SELECT 1
              FROM relacionamento r
              WHERE r.idquestao = q.id AND r.tabela = 'disciplina'
             );