我有两个表,其中一个名为 participants_tb,第二个名为 allocation_tb。在 participants_tb 上,我的列为 participant_id、name、username。 在 allocation_tb 下,我的列为 allocation_id、sender_username、receiver_username、done。 done 列包含以下三个数字中的任何一个:0、1、2。
我用这个sql语句来获取我的值
SELECT *, COUNT(done) d
FROM participants_tb
JOIN allocation_tb ON (username=receiver_username)
WHERE done = 0 || done = 1
GROUP BY receiver_username
它工作得很好,我的问题是,我希望它还包括参与者的信息,这些信息在 participants_tb 中但不在 allocation_tb 中。我尝试使用 left outer join 但它没有按预期工作,因为我希望它包括仅在 participants_tb 但不在 allocation_tb 中的参与者,因为 done 在 allocation_tb 中的 where 子句中,它不会包含那些信息。
最佳答案
你似乎想要:
SELECT p.*, COUNT(a.done) as d
FROM participants_tb p LEFT JOIN
allocation_tb a
ON p.username = a.receiver_username) AND
a.done IN (0, 1)
GROUP BY p.participant_id;
注意事项:
LEFT JOIN
保留所有参与者。GROUP BY
需要在第一个表上。- 您可以将
SELECT p.*
与GROUP BY
一起使用——假设GROUP BY
键是唯一的(或主键). - 所有列都应该是合格的。
IN
是表达您的逻辑的一种更简单的方式。
关于mysql - sql语句从两个不同的表中获取信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55082175/