我们是非政府组织,我们每个月都有捐赠者进行捐赠,所以我想显示一张表格,显示捐赠者的姓名和所有月份,如果他本月捐赠,则每个月都为真,否则为假
类似的东西
+-------+-----+-----+-----+-----+-----+
| Donor | Jan | Feb | Mar | Apr | May |
+-------+-----+-----+-----+-----+-----+
| A | 1 | 1 | 0 | 1 | 1 |
| B | 0 | 1 | 0 | 1 | 1 |
| C | 1 | 0 | 0 | 1 | 1 |
| D | 1 | 1 | 0 | 1 | 0 |
+-------+-----+-----+-----+-----+-----+
现在我在mysql数据库中制作2个表: 1)-捐助者 2)-Donation_Months
捐助者:
+-----+------+
| id | name |
+-----+------+
| 1 | A |
| 2 | B |
| 3 | C |
| 4 | D |
+-----+----- +
Donation_Months:
+-------+-------+-------+
| dm_id | do_id | month |
+-------+-------+-------+
| 1 | 2 | Jan |
| 2 | 2 | Feb |
| 3 | 2 | Mar |
| 4 | 2 | Apr |
+-------+-------+-------+
此表显示,第二个捐赠者(B)在这4个月内给了我们捐款
现在,我要使 Donors表与 Donation_Months表相关联的sql语句,并在顶部表格中显示结果。
在这里,我想为每个供体获得很多行,但我希望将它们显示为一个循环或一行
我该怎么做? 我尝试了很多方法,但没有这样的目的
SELECT accounts.*, (SELECT * FROM donation_months where donation_months.domo_account_id = accounts.account_id) AS months FROM `accounts`
帐户=捐助者
我想做的主意,我想基于供体ID获得第二张表的结果数组,并将其作为文本存储在这样的temp列中
+-------+------------------------+
| Donor | temp_months |
+-------+------------------------+
| A | () |
| B | (Jan, Feb, Mar, Apr) |
| C | () |
| D | () |
+-------+------------------------+
预先感谢
答案 0 :(得分:1)
一种解决方案可能是我们条件聚合:
SELECT
d.name,
COALESCE(MAX(m.month = 'Jan'), 0) Jan,
COALESCE(MAX(m.month = 'Fev'), 0) Fev,
COALESCE(MAX(m.month = 'Mar'), 0) Mar,
COALESCE(MAX(m.month = 'Apr'), 0) Apr,
COALESCE(MAX(m.month = 'May'), 0) May
FROM
donors d
CROSS JOIN (SELECT DISTINCT month FROM Donation_Months) x
LEFT JOIN Donation_Months m ON m.do_id = d.id
GROUP BY d.name;
根据您编辑的帖子,您可能希望使用GROUP_CONCAT
在一个列中显示所有月份,例如:
SELECT
d.name,
GROUP_CONCAT(DISTINCT m.month ORDER BY m.dm_id) temp_months
FROM
donors d
CROSS JOIN (SELECT DISTINCT month FROM Donation_Months) x
LEFT JOIN Donation_Months m ON m.do_id = d.id
GROUP BY d.name;