我有这样的事情:
(SELECT COUNT(*) AS total FROM `transactions` WHERE
`asset`='u_{$user_id}' GROUP BY id)
UNION DISTINCT
(SELECT COUNT(*) AS total FROM transactions tr
INNER JOIN payments pa ON tr.asset = CONCAT('p_', pa.id)
WHERE pa.user_id = '{$user_id}'
GROUP BY tr.id)
它给1
现在像这样工作:
SELECT
(SELECT COUNT(*) FROM `transactions`
WHERE `asset`='u_{$user_id}')
+
(SELECT COUNT(*) FROM transactions tr
INNER JOIN payments pa ON tr.asset = CONCAT('p_', pa.id)
WHERE pa.user_id = '{$user_id}')
它给6
但我需要得到5
..,播种如何做出正确的查询?
当然,我可以通过 php 做到这一点,但是..如何通过 sql..?
真正的“和”和“或”条件无关紧要,它们可以正常工作,问题在于对 UNION 的查询进行计数。第二个查询正确计数 summ (1+5),但值与查询相交。第一个给出了第一个子查询的结果。所以,我需要在计数之前获得独特的结果......
在 php 中,它应该是这样的:我通过内部连接与支付获取交易 id 列表,而不是在循环中构造一个长查询,以获得类似SELECT COUNT(*) FROM transactions WHERE (*what i have now* OR id=$id_1 OR id=$id_2 OR id=$id_3 etc..)
UPD:已切割
解决!=)
SELECT COUNT(*) FROM(
SELECT tr.* FROM transactions tr
WHERE tr.asset='u_{$user_id}' OR (tr.liability='g' AND tr.l_info='{$user_name}')
UNION SELECT tr.* FROM transactions tr
INNER JOIN payments pa ON tr.asset = CONCAT('p_', pa.id)
WHERE pa.user_id = '{$user_id}' AND pa.status='100')
AS total
作为总重要!