使用下面的Sql查询,当所有表都有数据时,我可以获得成功的结果,但是在这个查询中,当transactions
表没有任何已保存的数据并且其为空时,我的查询返回空结果,但是我想要获取 null 或空列数据
SELECT transactions.id,
userEwallets.ewalletNumber,
userEwallets.currencySymbol,
transactions.money,
transactions.transactionType,
b.username AS toUser,
a.username AS sender
FROM transactions
JOIN userEwallets ON transactions.ewalletId = userEwallets.id
LEFT JOIN users AS b ON b.id = transactions.toUserId
LEFT JOIN users AS a ON a.id = transactions.fromUserId
WHERE transactions.userId = 37
当它不为空时,我得到这个结果:
id ewalletNumber currencySymbol money transactionType toUser sender
95 SHIRR9373036569 IRR 20 1 1 amin
最佳答案
您可以使用一行虚拟表。其他表应该保留连接到它。
SELECT transactions.id,
userEwallets.ewalletNumber,
userEwallets.currencySymbol,
transactions.money,
transactions.transactionType,
b.username AS toUser,
a.username AS sender
FROM (select 1) dummy
LEFT JOIN transactions ON transactions.userId = 37
LEFT JOIN userEwallets ON transactions.ewalletId = userEwallets.id
LEFT JOIN users AS b ON b.id = transactions.toUserId
LEFT JOIN users AS a ON a.id = transactions.fromUserId
如果你给它一个别名,你总是可以使用子查询来代替表名。请注意,您必须将左连接表的 WHERE 条件移至 ON 子句中 - 否则 MySQL 会将其转换为 INNER JOIN。
关于当 JOIN 的表之一没有任何数据时,MySql 返回空结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38934618/