在一个mysql查询中从多个表中选择数据

时间:2019-05-16 03:17:33

标签: mysql

我有三个桌子

1条政策

 | date       | policy_No  | client_no | premium | policy_type   |
 | 2019-01-23 | 10002      |  1570     | 4000    | New policy    |
 | 2019-03-15 | 10003      |  1570     | 16000   | Renewal policy|

2背书

  |date       |client_no | policy_no| premium| endorsement_type|
  |2019-02-17 |  1570    |  10002   | 2000   | Debit
  |2019-03-17 |  1570    |  10003   | -4000  | Credit        

3付款

  | date      | client_id | policy_no| amount|
  | 2019-03-16| 1570      | 10003    | 10000 |

预期结果

 |  date      | type              | amount|
 | 2019-01-23 | New Policy        |  4000 |
 | 2019-02-17 | Debit endorsement |  2000 |
 | 2019-03-15 | Renewal policy    | 16000 |
 | 2019-03-16 | Payment           | 10000 |
 | 2019-03-17 | Credit endorsement| -4000 |  

如何在一个MySQL查询中实现

4 个答案:

答案 0 :(得分:2)

我们可以在此处尝试使用联合查询:

SELECT date, policy_type AS type, premium AS amount FROM Policies
UNION ALL
SELECT
    date,
    CASE WHEN endorsement_type = 'Debit' THEN 'Debit endorsement'
         WHEN endorsement_type = 'Credit' THEN 'Credit endorsement' END,
    premium
FROM Endorsements
UNION ALL
SELECT date, 'Payment', amount FROM Payment
ORDER BY date;

答案 1 :(得分:-1)

您的表有2个公共字段,很难确定哪个用作主键或外键。但是,要从不同的表中选择字段,可以使用LEFT JOIN RIGHT JOIN INNER JOINFULL OUTER JOIN

您应该阅读this post from W3schools来确定哪个是最适合您的选择。

典型语法如下  SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;

答案 2 :(得分:-1)

希望,所有三个表都具有外键。因此,我们也可以像下面的代码一样使用JOIN概念,

<ng-container *ngIf="jellyDonut">
  Jelly Donut
</ngcontainer>

<ng-container *ngIf="!jellyDonut">
  Other stuff
</ngcontainer>

谢谢

答案 3 :(得分:-2)

尝试一下

svg.selectAll('g')
  .data(data["students"])
  .enter()
  .append('g')
  .attr("class", "g2")
  .selectAll('.g2')
  .data(d => (d3.entries(d["grades"]).map(obj => {
    obj['Name'] = d['Name']
    return obj;
  })))
  .enter()
  .append('circle')
  .attr('cx', v => {
    return xscale(v.key)
  })
  .attr('cy', d => {
    return yscale(d.Name)
  })
  .attr('r', v => {
    return sqrtScale(v.value)
  })
  .style('fill', 'red');