【问题标题】:php mysql select from 2 tables [closed]php mysql从2个表中选择[关闭]
【发布时间】:2018-02-09 21:29:13
【问题描述】:

我有 2 个 mysql 表

table1 - 付款

id   |  client_id  | payment | date
1  |   4 |        100   |  01.05.2017
2  |   4 |        120   | 05.05.2017

table2 - 发票

id |  client_id |  total |  invoice_nr |  date
1  |    4      |   350  |    0001     |  01.03.2017
2  |    4      |   400  |    0002    |  01.04.2017

如何按日期显示这样的结果

id   |    date |         payment  |  total |  invoice_nr
1    |    01.03.2017  |     null |    350  |     0001
2    |   01.04.2017  |     null |    400  |     0002
1    |    01.05.2017  |    100    |     null |      null 
2    |    05.05.2017  |    120    |     null |     null 

我尝试了一些方法,但出现了错误。

【问题讨论】:

标签: php mysql sql select


【解决方案1】:

您需要从两个表中union all 查询:

SELECT   `id`, `date`, `payment`, NULL AS `total`, NULL AS `invoice_nr`
FROM     `payments`
UNION ALL
SELECT   `id`, `date`, NULL AS `payment`, `total`, `invoice_nr`
FROM     `invoice`
ORDER BY `date` ASC

【讨论】:

    【解决方案2】:

    这对我有用

    SELECT 
    table2.id, 
    table2.date, 
    table2.payment, 
    table2.total,  
    table2.invoice_nr  
    from table1,table2 
    where 
    table1.id = table2.cliente_id 
    

    【讨论】:

    • 不要建议使用超过 25 年的连接方法使用 INNER JOIN ... ON 语法而不是逗号连接......逗号连接更难,更容易误会你的意思是 JOIN .
    • 这也是完全错误的。这将产生两行,而不是所需结果中的 4 行。
    猜你喜欢
    • 2016-02-25
    • 1970-01-01
    • 1970-01-01
    • 2013-04-30
    • 1970-01-01
    • 1970-01-01
    • 2015-11-03
    • 1970-01-01
    • 2014-10-28
    相关资源
    最近更新 更多