mySQL从两个表中选择并匹配结果

时间:2016-12-22 09:36:34

标签: mysql

我想

SELECT DISTINCT column1, column2 as t1

我想

SELECT column3 FROM table2 WHERE column4 = "1" AND column3 = (matches)t1.column1

我的查询应该如何?

SELECT DISTINCT column1, column2 FROM table1 as t1,
column3 FROM table2 WHERE column4 = "1" AND column3 = t1.column1

结果应该是包含column1数据的列表,该列表与column3和column4 = 1

中的数据匹配
Table1:                Table2:
-----------------------------------------
column1    column2     column3    column4
-----------------------------------------
001        Name        001        1      
002        Name        002        0
003        Name        004        1
005        Name        005        1
-----------------------------------------
Result: 001, 005     

错误:

  

语法错误或访问冲突:1064 SQL中有错误   句法;检查与MariaDB服务器对应的手册   正确使用语法的版本' FROM table2 WHERE column4 =   ' 1' AND column3 = t1.column1'在第1行

2 个答案:

答案 0 :(得分:2)

select distinct
   t1.column1,
   t1.column2,
   t2.column4
from
   table1 as t1
inner join
   table2 as t2 on t2.column3 = t1.column1
where
   column4 = "1"

答案 1 :(得分:0)

您的查询应如下所示:

SELECT DISTINCT
    t1.column1, t1.column2, t2.column3, t2.column4
FROM
    table1 AS t1,
    table2 AS t2
WHERE
    t2.column4 = '1'
        AND t2.column3 = t1.column1