繁体   English   中英

MySQL从一个表中选择数据,条件在其他表中

[英]MySQL select data from one table where conditions are in other tables

我的SQL生锈了,我必须解决一个问题。 我在三个表中有数据,如下所示。 在table1和table2列中,用户名都是唯一的!

我需要列出所有具有max(year)= 2016(在表3中)的用户(来自表1)的地址,并且还必须是类型= 0(来自表2)的用户。 根据示例中的数据,结果应为: address3

知道如何使用单个SQL命令执行此操作吗? 我可以(并且我已经完成了)编写一个php脚本,但是它应该是一个(复杂的)SQL命令!

我尝试了联接,内部联接等,但是,至少作为SQL用户,我的知识有限。

table1             table2         table3        
---------|--------  --------|----  --------|-----
username |address   username|type  username| year
---------|--------  --------|----  --------|-----
user1    |address1   user1  | 1    user1   | 2015
user2    |address2   user2  | 1    user1   | 2016
user3    |address3   user3  | 0    user1   | 2017
user4    |address4   user4  | 0    user2   | 2015
                                   user2   | 2016
                                   user3   | 2015
                                   user3   | 2016
                                   user4   | 2014
                                   user4   | 2015
select table1.address
from table1
     inner join table2 on table2.username = table1.username
     inner join 
                (select username, max(date) maxDate
                 from table3 
                 group by username) t3 on t3.username = table1.username
where table2.type = 0
      and t3.maxDate = 2016;

要么

select table1.address
from table1
     inner join table2 on table2.username = table1.username
     inner join 
                (select username, max(date) maxDate
                 from table3 
                 group by username
                 having max(date) = 2016) t3 on t3.username = table1.username
where table2.type = 0;

您可以尝试一下,队友:

SELECT
-- I need to list addresses of all users (from table1)
    t1.username, t1.address
FROM
    table1 t1
    INNER JOIN table2 t2 ON t2.username = t1.username
    INNER JOIN table3 t3 ON t3.username = t2.username
-- and also must be of type=0 (from table2)
WHERE t2.type = 0
-- that have max(year)=2016
HAVING MAX(t3.year) = 2016;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM