我加入了多个表。您可以在此演示中找到表和 MySQL 查询。
这些是表格:
用户
id name 1 abc 2 xyz 3 pqr
朋友
user_id friend_id 1 2 1 3 2 3
收藏
id user_id friend_id amount 1 1 2 100 2 2 1 -100 3 2 3 200 4 3 2 -200 5 1 3 300 6 3 1 -300
账单
id use_id(bill_creator) 1 1 2 2 3 2
bill_person
id bill_id user_id 1 1 1 2 1 2 3 1 3 4 2 2 5 2 3 6 3 2 6 3 1
到目前为止,我已经提出了这个查询:
SELECT mf.id
, mf.name
, c.amount AS amount,count(bp.user_id) AS no_common_bills
FROM (
SELECT fr.user_id AS user_id
, fr.friend_id AS friend_id
FROM friend fr
JOIN users fru
ON fru.id = fr.user_id
WHERE fru.id IN (1)
UNION
SELECT fl.friend_id AS user_id
, fl.user_id AS friend_id
FROM friend fl
JOIN users flf
ON flf.id = fl.friend_id
WHERE flf.id IN (1)
) f
JOIN users mf
ON mf.id = f.friend_id
LEFT
JOIN collection c
ON c.friend_id = mf.id
AND c.user_id = f.user_id
LEFT JOIN bill_person bp
ON bp.user_id=f.user_id AND c.friend_id = mf.id
GROUP BY mf.id
ORDER BY mf.id
我这个查询的输出是
id NAME AMOUNT NO_COMMON_BILLS
2 XYZ 100 2
3 PQR 300 2
但我想要这个结果:
id NAME AMOUNT NO_COMMON_BILLS
2 XYZ 100 2
3 PQR 300 1
我在NO_COMMON_BILLS得到错误的输出。除此之外,所有值都是正确的。