简体   繁体   English

无法计算联接表mySQL的结果

[英]Can't Count results from Joined Table mySQL

i followed 3 others SO answers, and they say it works.. but here not... here is my problem, i have this QUERY: 我遵循了另外3个答案,他们说它有效..但是这里不...这是我的问题,我有此查询:

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

This is there result of query: 这是查询结果: 查询结果

Until here, it was perfect.. now i need know how much rows returned... i changed the query to this: 直到这里,它都是完美的..现在我需要知道返回了多少行...我将查询更改为:

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

And got this error: 并得到此错误:

计数错误

Why i cant count how much rows did i get? 为什么我不能数出我得到了多少行?

UPDATE: I did try do this query also: 更新:我也尝试过执行此查询:

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

And get this as result: 并得到以下结果:

计数(*)结果

You can change it like this: 您可以这样更改:

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
)

Your query is probably better written as: 您的查询最好写成:

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

This should be more efficient than your query, if you have an index on relacionamento(idquestao, tablea) (which you would want anyway for the join ). 如果您在relacionamento(idquestao, tablea)上有一个索引relacionamento(idquestao, tablea)无论如何要使用join ),这应该比查询更有效。 And, it doesn't use select * with group by , which just generally looks wrong. 而且,它不将select *group by ,这通常看起来是错误的。

Then, to get the count, you can just do count(*) : 然后,要获取计数,您可以执行count(*)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM