我想从左连接sql获得不同的记录。
SELECT sd.bill_amount, mr.payment_amount
FROM event_mgmt_settlement_details sd
LEFT JOIN event_mgmt_registration mr
ON sd.order_id = mr.order_id
在这个sql中,我可以从2个具有相同order_id的表中获取所有记录,但是某些sd.order_id或mr.order_id具有彼此不具有的唯一ID,我如何获取这些记录?
答案 0 :(得分:0)
SELECT sd.bill_amount, mr.payment_amount
FROM event_mgmt_settlement_details sd , event_mgmt_registration mr
答案 1 :(得分:0)
试试这个:
SELECT sd.bill_amount, mr.payment_amount
FROM event_mgmt_settlement_details sd ,event_mgmt_registration mr
所以如果你有sd.order_id有1到11而mr.order_id有1到10,那么结果是:
1:1, 2:1, 3:1, 等.. 11:10
答案 2 :(得分:0)
从两个表中查找不匹配记录的一种方法是执行union all
,然后选择group_by
的数据。如果表具有相同的列名,这种方式很有效。由于你有不同的名字,所以它需要一些调整,也许更好的做一个身份,以查看记录来自哪个表。
select
order_id,
amount,
table_name
from
(
select
order_id,
bill_amount as amount,
'Table1' as table_name
from event_mgmt_settlement_details
union all
select
order_id,
payment_amount as amount,
'Table2' as table_name
from event_mgmt_registration
)x
GROUP BY order_id HAVING COUNT(*) = 1;
<强> DEMO 强>
答案 3 :(得分:0)
我想你想要:
SELECT sd.order_id, sd.bill_amount, 'event_mgmt_settlement_details'
FROM event_mgmt_settlement_details sd
LEFT JOIN event_mgmt_registration mr
ON sd.order_id = mr.order_id
WHERE mr.order_id is null
UNION ALL
SELECT mr.order_id, mr.payment_amount, 'event_mgmt_registration'
FROM event_mgmt_settlement_details sd
RIGHT JOIN event_mgmt_registration mr
ON sd.order_id = mr.order_id
WHERE sd.order_id is null
由于MySql不支持完全外连接,因此联合左连接和右连接。
答案 4 :(得分:0)
您可以针对不同的join类型考虑以下架构:
SELECT sd.bill_amount, mr.payment_amount
FROM event_mgmt_settlement_details sd
FULL OUTER JOIN event_mgmt_registration mr
ON sd.order_id = mr.order_id
WHERE sd.order_id IS NULL OR mr.order_id IS NULL;