来自两个不同表的 Select 行,但使用 php 和 MySQL 按日期排序
Select rows from two different tables but order by date using php and MySQL
我有两个表;
我正在尝试制作一份对账单(如银行对账单)来显示所有费用和所有付款。费用和付款需要根据 statement_date 字段按日期顺序显示。
我很确定我需要使用 'unions',但我似乎找不到解决方案。
我目前的努力是;
$statement_sql = "(SELECT * FROM accounts_tenant_charge)
UNION
(SELECT * FROM accounts_tenant_payment)
ORDER BY statement_date";
提前致谢。
您必须进行嵌套查询。首先,您根据 table 进行联合查询并放入内部查询。然后,您进行 SELECT 查询并放入外部。不要忘记为外部查询提供别名 table。
你可以试试这个代码:
SELECT * FROM
(
(SELECT * FROM accounts_tenant_charge)
UNION
(SELECT * FROM accounts_tenant_payment)
) a
ORDER BY a.statement_date ASC
您的表有不同的列数,因此您不能通过 select *
立即合并它们。您必须 select 两个表中的列数相等。喜欢:
select
tenant_charge_id as `id`,
tenant_charge_date as `date`,
tenant_charge_total_amonunt as `amount`
union
select
tenant_payment_id,
tenant_payment_date,
tenant_payment_amount
order by
`date` asc
感谢您的帮助。以下查询对我有用;
SELECT tenant_charge_date as statement_date, tenant_charge_id as reference, tenant_charge_total_amount as debit, NULL as credit, 'Charge' as type FROM accounts_tenant_charge
UNION ALL
SELECT tenant_payment_date as statement_date, tenant_payment_id as reference, NULL as debit, tenant_payment_amount as credit, 'Payment' as type FROM accounts_tenant_payment
ORDER BY statement_date
我有两个表;
我正在尝试制作一份对账单(如银行对账单)来显示所有费用和所有付款。费用和付款需要根据 statement_date 字段按日期顺序显示。
我很确定我需要使用 'unions',但我似乎找不到解决方案。
我目前的努力是;
$statement_sql = "(SELECT * FROM accounts_tenant_charge)
UNION
(SELECT * FROM accounts_tenant_payment)
ORDER BY statement_date";
提前致谢。
您必须进行嵌套查询。首先,您根据 table 进行联合查询并放入内部查询。然后,您进行 SELECT 查询并放入外部。不要忘记为外部查询提供别名 table。
你可以试试这个代码:
SELECT * FROM
(
(SELECT * FROM accounts_tenant_charge)
UNION
(SELECT * FROM accounts_tenant_payment)
) a
ORDER BY a.statement_date ASC
您的表有不同的列数,因此您不能通过 select *
立即合并它们。您必须 select 两个表中的列数相等。喜欢:
select
tenant_charge_id as `id`,
tenant_charge_date as `date`,
tenant_charge_total_amonunt as `amount`
union
select
tenant_payment_id,
tenant_payment_date,
tenant_payment_amount
order by
`date` asc
感谢您的帮助。以下查询对我有用;
SELECT tenant_charge_date as statement_date, tenant_charge_id as reference, tenant_charge_total_amount as debit, NULL as credit, 'Charge' as type FROM accounts_tenant_charge
UNION ALL
SELECT tenant_payment_date as statement_date, tenant_payment_id as reference, NULL as debit, tenant_payment_amount as credit, 'Payment' as type FROM accounts_tenant_payment
ORDER BY statement_date