如何在mysql的行结果中存储联接表的结果数组?

时间:2019-02-13 15:15:25

标签: php mysql sql

我们有3张桌子:

  1. 捐款
  2. 目的
  3. 费用

捐赠:

+--------+------+
| do_id  | name |
+--------+------+
|  1     |  A   |
|  2     |  B   |
|  3     |  A   |
|  4     |  D   |
|  5     |  B   |
|  6     |  B   |
|  7     |  A   |
|  8     |  B   |
+--------+----- +

目的:

+-------+-------+--------+
| pu_id | do_id | purpose|
+-------+-------+--------+
|   1   |   2   |  abc   |
|   2   |   2   |  def   |
|   3   |   2   |  gih   |
|   4   |   3   |  jkl   |
+-------+-------+--------+

费用:

+-------+-------+---------+
| ex_id | do_id | expense |
+-------+-------+---------+
|   1   |   2   |   abc   |
|   2   |   2   |   def   |
|   3   |   2   |   gih   |
|   4   |   3   |   jkl   |
+-------+-------+---------+

现在,我要查询以获取捐赠方 B 的所有捐赠,并加入目的表以获取与每个 donation_id 相关的所有目的加入费用表以获取与 donation_id 相关的所有费用,并将所有这些费用独立地放入每个循环中

Row number 0

donation_id = 1
array(purposes)
array(expenses)

Row number 1

donation_id = 2
array(purposes)
array(expenses)

Row number 2

donation_id = 3
array(purposes)
array(expenses)

Row number 3

donation_id = 4
array(purposes)
array(expenses)

这是我的尝试:

SELECT *, (
    SELECT * 
    FROM `donation_purposes` 
    WHERE `donation_purposes`.`dopu_donation_id` = 4
) AS `purposes` 
FROM `donations` 
WHERE `donation_id` = '4'

预先感谢

2 个答案:

答案 0 :(得分:0)

您应该能够使用MySQL aggregate function JSON_ARRAYAGG()使用汇总查询来解决这个问题,例如:

SELECT
    d.do_id,
    JSON_ARRAYAGG(p.purpose) purposes,
    JSON_ARRAYAGG(e.expense) expenses
FROM donations d
INNER JOIN purposes p ON p.do_id = d.do_id 
INNER JOIN expense e  ON e.do_id = d.do_id 
GROUP BY d.do_id

我要避免在数组中重复值,并且由于JSON_ARRAYAGG()(很难)不支持DISTINCT选项,因此可以将聚合移至子查询,例如:

SELECT
    d.do_id,
    p.agg purpose,
    e.agg expenses
FROM donations d
INNER JOIN (
  SELECT do_id, JSON_ARRAYAGG(purpose) agg FROM purposes GROUP BY do_id
) p ON p.do_id = d.do_id 
INNER JOIN (
   SELECT do_id, JSON_ARRAYAGG(expense) agg FROM expense GROUP BY do_id
) e  ON e.do_id = d.do_id 

demo on DB Fiddle 返回:

| do_id | purpose               | expenses              |
| ----- | --------------------- | --------------------- |
| 2     | ["abc", "def", "gih"] | ["abc", "def", "gih"] |
| 3     | ["jkl"]               | ["jkl"]               |

答案 1 :(得分:0)

  • 第一个选择查询目的

    SELECT purposes.* FROM purposes
    LEFT JOIN donations
    ON purposes.do_id = donations.do_id
    WHERE donations.do_id = '2' //This depends on the id of the donation
    ORDER BY purposes.do_id ASC
    
  • 第二次选择查询费用

    SELECT expense.* FROM expense
    LEFT JOIN donations
    ON expense.do_id = donations.do_id
    WHERE donations.do_id = '2' //This depends on the id of the donation
    ORDER BY expense.ex_id ASC
    

生成的所有查询均来自您提供的表结构,但是您的问题很模糊!