如何在MYSQL中对另一个查询结果进行查询?

时间:2018-10-04 13:32:29

标签: php mysql

我进行了这样的查询以通过连接3个表来获得结果

查询1

SELECT a.user_id, a.nick_id, count(b.invoice_id) AS INVOICES, sum(b.purchase_amount) AS PURCHASES, c.sponsor_id, c.user_first_name, c.user_last_name

FROM table1 a
INNER JOIN table2 b ON a.user_id = b.user_id
INNER JOIN table3 c ON a.user_id = c.user_id

WHERE b.purchase_date BETWEEN '2018-09-01 00:00:00' AND now() and a.user_id IS NOT NULL GROUP BY a.user_id ORDER BY PURCHASES DESC

表1(示例)

user_id | nick_id

1 | AGENT1

2 | AGENT2

3 | AGENT3

表2(示例)

user_id | invoice_id | purchase_amount | purchase_date

1 | IN001 | 500 | 2018-09-01 14:58:33

2 | IN002 | 1000 | 2018-09-18 22:46:12

表3(示例)

user_id | sponsor_id | user_first_name | user_last_name

2 | 1 | John | Doe

3 | 1 | Harry | Wilson

4 | 2 | Peter | Bennington

5 | 2 | Daisy | Cooper

现在根据[QUERY 1]的结果,我想执行[QUERY 2]

查询2

SELECT  sponsor_id, user_id, user_first_name, user_last_name
FROM
(SELECT * FROM table3 ORDER BY sponsor_id, user_id) table3,
(SELECT @pv := '1') initialisation WHERE find_in_set(sponsor_id, @pv) > 0
AND @pv := concat(@pv, ',', user_id)

之后,我会得到想要的结果。但是我想在一个查询中一次执行两个查询。

0 个答案:

没有答案