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

时间:2017-02-16 23:44:22

标签: mysql

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

我需要列出所有用户(来自table1)的地址,这些地址的最大值(年份)= 2016(表3),且必须是type = 0(来自table2)。 根据示例中的数据,结果应为: 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

2 个答案:

答案 0 :(得分:0)

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;

答案 1 :(得分: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;