我的一个查询有问题,在我的脑海中找不到解决方案,我尝试了很多方法,但无法达到预期的结果。这是我的表结构:
+----------------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------+---------------+------+-----+---------+----------------+
| accounts_id | int(11) | NO | PRI | NULL | auto_increment |
| portfolio_id | int(11) | NO | | NULL | |
| contest_id | int(11) | NO | | NULL | |
| user_id | int(11) | NO | | NULL | |
| company_id | int(11) | NO | | NULL | |
| buy_price | decimal(10,2) | YES | | NULL | |
| buy_amount | int(11) | YES | | NULL | |
| buy_commision | decimal(10,2) | YES | | NULL | |
| buy_date | date | YES | | NULL | |
| sell_price | decimal(10,2) | YES | | NULL | |
| sell_amount | int(11) | YES | | NULL | |
| sell_commision | decimal(10,2) | YES | | NULL | |
| sell_date | date | YES | | NULL | |
+----------------+---------------+------+-----+---------+----------------+
我想找到每个买卖的已实现 yield ,所以我使用了这个查询:
SELECT
a.company_id,
a.buy_price,
a.buy_amount,
a.buy_commision,
a.buy_date,
a.sell_price,
a.sell_amount,
a.sell_commision,
a.sell_date,
(((a.sell_amount*a.sell_price)-(a.sell_amount*a.sell_price)*.5/100)-((b1.buy_price*a.sell_amount)+ (b1.buy_price*a.sell_amount)*.5/100)) as realized
FROM contest_accounts AS a
RIGHT join contest_accounts as b1
on a.portfolio_id = b1.portfolio_id
WHERE a.user_id = 1
AND a.contest_id = 2;
这给了我这样的结果: http://sqlfiddle.com/#!2/d8e2c/2
但我想要这样的结果:
+------------+-----------+------------+---------------+------------+------------+-------------+----- -----------+------------+-------------+
| company_id | buy_price | buy_amount | buy_commision | buy_date | sell_price | sell_amount | sell_commision | sell_date | realized |
+------------+-----------+------------+---------------+------------+------------+-------------+----- -----------+------------+-------------+
| 1 | 6.80 | 300 | 10.20 | 2014-03-15 | NULL | NULL | NULL | NULL | NULL |
| 1 | NULL | NULL | NULL | NULL | 6.80 | 200 | 6.80 | 2014-03-15 | -13.6000000 |
| 1 | NULL | NULL | NULL | NULL | 6.80 | 100 | 3.40 | 2014-03-15 | -6.8000000 |
| 1 | 6.80 | 100 | 3.40 | 2014-03-15 | NULL | NULL | NULL | NULL | NULL |
| 1 | NULL | NULL | NULL | NULL | 6.50 | 100 | 3.25 | 2014-03-18 | -36.6500000 |
3 | 20.10 | 200 | 20.10 | 2014-03-15 | NULL | NULL | NULL | NULL | NULL |
| 3 | NULL | NULL | NULL | NULL | 19.80 | 100 | 9.90 | 2014-03-16 | -49.9500000 |
主要问题是当前查询返回如此多的空值,但我想要具有购买日期或实现 yield 的结果没有那么多空值,我知道我搞乱了连接,但不知道如何才能实现我想要的结果。请检查 sqlfiddle 中的示例数据和我的查询结果。
最佳答案
将条件 buy_date IS NOT NULL
添加到 where 子句。这只会为您提供 buy_date 不为空的记录。您也可以为其他记录添加类似的条件。
我认为您可以将RIGHT JOIN
更改为INNER JOIN
。仅当 a
中可能不存在 b
的匹配记录时,才使用 RIGHT JOIN
。在这种情况下,a 中始终有一条记录,因为您已经通过在 where 子句中使用条件 a.user_id = 1
隐式过滤掉了其他情况。
实际上,更改为 INNER JOIN
不会改变结果,但可能会加快查询速度并使其更具可读性(根据我的口味)。
关于php - Mysql Right Join 返回不必要的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22486133/