[英]How to show all records from one table even if they don't match WHERE clause with JOIN
I have a problem with a consult im trying to achieve : 我在尝试实现以下咨询时遇到问题:
SELECT [columns] FROM table1 LEFT/RIGHT JOIN table2 ON table1.id_user = table2.id [WHERE clause] GROUP BY column
An example of what I want this consult to do is shown below: 我希望此咨询执行的示例如下所示:
Having this records in table1 : 在table1中有此记录:
id | id | id_user | id_user | user | 用户| value 值
1 | 1 | 1 | 1 | name1 | 名称1 | 10 10
2 | 2 | 1 | 1 | name1 | 名称1 | 10 10
3 | 3 | 1 | 1 | name1 | 名称1 | 11 11
4 | 4 | 1 | 1 | name1 | 名称1 | 10 10
5 | 5 | 2 | 2 | name2 | name2 | 11 11
6 | 6 | 2 | 2 | name2 | name2 | 11 11
And this ones in table 2: 表2:
id | id | user 用户
1 | 1 | name1 名称1
2 | 2 | name2 名称2
I would like to get how many records exist of every user given a value, for exmample if we look for value 10 I would like to get : 我想获得给定值的每个用户有多少条记录,例如,如果我们寻找值10,我想得到:
name1 | 名称1 | 3 3
name2 | name2 | 0 0
I've tried with LEFT and RIGHT JOIN but didn't work, I just got this as are the only records that match the WHERE clause i guess: 我已经尝试过使用LEFT和RIGHT JOIN,但是没有用,我得到了,因为我猜这是唯一与WHERE子句匹配的记录:
name1 | 名称1 | 3 3
And not result for name2. 而不是name2的结果。
I've been unsuccessfully looking for a solution before taking my problem here, hope someone can help me with this issue :) 在这里提出问题之前,我一直没有找到解决方案,希望有人可以帮助我解决这个问题:)
Sorry for the bad english. 对不起,英语不好。 I really appreciate any help you can provide 我非常感谢您可以提供的任何帮助
not the most efficient query but this should work 不是最有效的查询,但这应该可以工作
select user, (select count(*) from table1 b where b.id_user=a.id and b.value=10)
from table2 a
often, because this query is so inefficient, i will join the results on the client instead of trying to do it in sql. 通常,因为此查询效率很低,所以我会将结果加入客户端,而不是尝试在sql中进行。 the process would go something like this. 该过程将是这样的。
{'user': name, 'count': 0}
遍历查询1,并将结果存储在一个看起来像{'user': name, 'count': 0}
it always depends on the size of the result sets and maybe hardware involved, but often this has been faster albeit quite a bit more complex to write in the code. 它总是取决于结果集的大小以及可能涉及的硬件,但这通常更快,尽管用代码编写要复杂得多。
Try this. 尝试这个。
SELECT t2.user,SUM(CASE WHEN t2.id=t1.id_user THEN 1 ELSE 0 END) AS TotalRecords
FROM table2 t2
LEFT JOIN table1 t1 ON t2.id =t1.id_user
GROUP BY t2.id
HAVING t1.value=10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.