选择ID在另一个表中且状态= 1的记录

时间:2016-12-29 18:15:30

标签: mysql sql

我需要获取table1.user在table2.userid和table2.country = 8以及table2.status = 1

中的所有记录

这是我数据库中的示例数据

表1

id  user
--  ----
1    12
2    23
3    34
4    32
5    85
6    38

表2

id  userid  country_id  status
--  ----      -----      ----
1    12         5         1
2    12         8         1
3    85         8         1 
4    38         8         0         
5    38         7         1
6    23         8         1
7    23         4         1

在这种情况下,我应该只获得table2中的id#3

3 个答案:

答案 0 :(得分:3)

内部联接将仅执行两个表中匹配记录的作业。

SELECT *
FROM table1 t1
INNER JOIN table2 t2 on t1.user = t2.userid
WHERE t2.country=8 and t2.status=1

答案 1 :(得分:0)

你的意思是

"获取table1.user在table2.userid
中的所有记录      table2.country = 8,table2.status = 1?"

如果是,那么:

Select * from table1 t1
Where Exists(Select * from table2
             Where userId = t1.user
                and country  = 8
                and status = 1)

答案 2 :(得分:0)

要实现这一点非常简单,您只需要使用内部联接。 SQL JOIN子句用于组合来自两个或多个表的行,基于它们之间的公共字段。

在你的情况下,INNER JOIN将返回table2中满足连接条件的所有行。

有关更详细的说明和示例,请访问以下链接:http://www.w3schools.com/sql/sql_join.asp

基于您对Adam的方法的回应" 我尝试了这个,但它没有工作,是的,它获取了记录,但表2中的id#2也包括在内。我需要得到的是table2中的id#3。谢谢:)"。我将我的SQL查询更改为:

SELECT 
  * 
FROM 
  table1
INNER JOIN
 table2
ON
table1.user = table2.userid
WHERE
table2.userid = 85

我假设您只想要table2中特定用户标识的数据

相关问题