Php 如何修复mysql子查询显示
这是我的示例表: 对于用户Php 如何修复mysql子查询显示,php,mysql,Php,Mysql,这是我的示例表: 对于用户 SELECT User.username, IFNULL(SUM(credit) - SUM(debit), 0) AS total, ( SELECT SUM(Bid.credit) - SUM(Bid.debit) AS freebids FROM users AS User LEFT JOIN bids AS Bid ON Bid.user_i
SELECT User.username,
IFNULL(SUM(credit) - SUM(debit), 0) AS total,
( SELECT SUM(Bid.credit) - SUM(Bid.debit) AS freebids
FROM users AS User
LEFT
JOIN bids AS Bid
ON Bid.user_id = User.id
WHERE Bid.type = 2
) AS FreeBids,
( SELECT SUM(Bid.credit) - SUM(Bid.debit) AS Normalbids
FROM users AS User
LEFT
JOIN bids AS Bid
ON Bid.user_id = User.id
WHERE Bid.type = 0
OR Bid.type = 1
) AS NormalBids
FROM users AS User
LEFT
JOIN bids AS Bid
ON Bid.user_id = User.id
GROUP
BY User.id
投标
id username
1 user1
2 user2
3 user3
4 user4
但是我在显示子查询(Freebids和Normalbids)时遇到问题,因为它们都具有相同的值。以下是示例显示:
id user_id debit credit type
1 1 0 10 0
2 1 1 5 2
3 1 1 0 2
4 3 0 10 0
6 2 0 10 0
7 4 1 10 0
8 4 1 0 1
我想不出我在我的查询中去了哪里。
有什么解决我问题的建议吗?
谢谢您的帮助。子查询和联接的组合实际上没有意义:对于外部查询的每一行,每个子查询将返回相同的多行集合,而不是返回与外部查询的行对应的正确单个值 有几种方法可以满足您的需要,但我认为最简单的方法是完全消除连接,并使用相关子查询:
username total FreeBids NormalBids
user1 10 12809 965
user2 20 12809 965
user3 9 12809 965
user4 0 12809 965
每个子查询引用外部查询中的
用户
记录,使所有内容都井然有序。显示所有相同值的原因是外部查询中的用户
表和内部查询中的用户
表之间没有区别。他们都有相同的别名。您必须通过为外部用户
表或内部用户
表分配不同的别名(例如u
)来区分它们,以便子查询知道外部值要引用哪个表:
SELECT User.username,
( SELECT IFNULL(SUM(credit) - SUM(debit), 0)
FROM bids AS Bid
WHERE Bid.user_id = User.id
) AS total,
( SELECT IFNULL(SUM(credit) - SUM(debit), 0)
FROM bids AS Bid
WHERE Bid.user_id = User.id
AND Bid.type = 2
) AS FreeBids,
( SELECT IFNULL(SUM(credit) - SUM(debit), 0)
FROM bids AS Bid
WHERE Bid.user_id = User.id
AND Bid.type IN (0, 1)
) AS NormalBids
FROM users AS User
;
话虽如此,使用这样的子查询是非常低效的,因为它们需要为users
表中的每一行执行(我们说的是整个表需要加入和过滤的次数与用户数一样多)
使用条件聚合可以更高效地重写查询:
... FROM users AS u ...
这基本上是说:只有当类型为x
value时,才能对贷方/借方进行求和,并且您可以在任何条件下求和/计数/平均/等等,只要使用一个表联接即可
该示例相当不错,但可以通过提供as SQL
INSERT
语句而不是表转储来改进。所需的结果不需要是SQL。
SELECT
a.username,
IFNULL(SUM(b.credit) - SUM(b.debit), 0) AS total,
SUM(IF(b.type = 2, b.credit, 0)) - SUM(IF(b.type = 2, b.debit, 0)) AS freebids,
SUM(IF(b.type IN (0,1), b.credit, 0)) - SUM(IF(b.type IN (0,1), b.debit, 0)) AS normalbids
FROM users a
LEFT JOIN bids b ON a.id = b.user_id
GROUP BY a.id, a.username