[英]mysql - get data from another tabel according to search?
I have 2 tables that use the same ID as PK , I have make a "where" question in table2 and got a resault 我有2个使用与PK相同的ID的表,我在table2中提出了“ where”问题,并得到了恢复
now I wnat to use the ID I got and see what is the Name from table 1 现在我要使用我获得的ID,看看表1中的名称是什么
table 1 (Users) is
ID Name
1 David
2 Guy
3 Robert
4 Helen
table 2 (history_Users_daily )is
ID ADDED_Money User_Date
1 0 2019-02-07
1 1 2019-02-08
1 0 2019-02-10
2 0 2019-02-07
2 0 2019-02-13
3 5 2019-02-12
4 0 2019-02-12
4 0 2019-02-13
this is the what I did on table 2: 这就是我在表2上所做的:
SELECT ID,SUM(ADDED_Money) AS Total_Money_7_Days
from
v7.history_Users_daily
where ( com_id = '1' and User_DATE >= date(curdate() - 7) )
GROUP BY ID
HAVING Total_Money_7_Days < '2'
order by Total_Money_7_Days ;
when I run this I see all the ID that have less then 2 当我运行它时,我看到所有小于2的ID
this is the result I'm getting : 这是我得到的结果:
ID Total_Money_7_Days
1 1
2 0
4 0
now I want to see what is the Name of each ID according to table 1 现在我想看看根据表1每个ID的名称是什么
so in the final I will get this : 所以最终我会得到这个:
ID Name Total_Money_7_Days
1 David 1
2 Guy 0
4 Helen 0
I have try all kinds of "Join"(examples I have found on google, but none of them work ) 我尝试了各种“加入”(例如我在google上找到的示例,但都不起作用)
what I need to do? 我需要做什么?
Thanks , 谢谢 ,
select t2.Id, t1.Name, t2.Total_Money_7_Days
from users t1
Join (SELECT ID,SUM(ADDED_Money) AS Total_Money_7_Days
from
v7.history_Users_daily
where ( com_id = '1' and User_DATE >= date(curdate() - 7) )
GROUP BY ID
HAVING Total_Money_7_Days < '2'
order by Total_Money_7_Days
) t2
on t2.Id = t1.Id
You can just JOIN
directly to the Users
table: 您可以直接将JOIN
到Users
表:
SELECT h.ID, u.Name, SUM(h.ADDED_Money) AS Total_Money_7_Days
FROM history_Users_daily h
JOIN Users u ON u.ID = h.ID
WHERE ( com_id = '1' AND User_DATE >= date(curdate() - 7) )
GROUP BY h.ID, u.Name
HAVING Total_Money_7_Days < '2'
ORDER BY Total_Money_7_Days DESC
Output 输出量
ID Name Total_Money_7_Days
1 David 1
2 Guy 0
4 Helen 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.