MySQL查询从第二个表中删除重复项
我有两个mysql表:表1和表2 表1:MySQL查询从第二个表中删除重复项,mysql,join,Mysql,Join,我有两个mysql表:表1和表2 表1: | c_id | name | email | | 1 | tom | t@t.com | 表2: | a_id | c_id | address | street | | 1 | 1 | 67 | home | | 2 | 1 | 68 | main | 如何创建mysql查询,选择table_1.name、table_1.email、table_2.address和table_2.s
| c_id | name | email |
| 1 | tom | t@t.com |
表2:
| a_id | c_id | address | street |
| 1 | 1 | 67 | home |
| 2 | 1 | 68 | main |
如何创建mysql查询,选择table_1.name、table_1.email、table_2.address和table_2.street,只返回一条记录,如:
| name | email | address | street |
| tom | t@t.com | 67 | home |
谢谢你的建议。
例如,T您应该使用SQL语句LEFT JOIN
SELECT name, email, address, street
FROM table1
LEFT JOIN table2
ON table1.c_id=table2.c_id;
使用name='tom'的可能选项,尝试以下操作:
SELECT table_1.name, table_1.email, table_2.address, table_2.street
FROM table_1
JOIN table_2
ON table_1.c_id = table_2.c_id
GROUP BY table_1.c_id
分组依据
将确定要使用哪个列对结果进行分组。B.T.W.如果您喜欢更改列标题,您可以添加作为
,后跟列标题名称(表1.name作为“First name”
)
表结构和样本数据:
CREATE TABLE table_1
(`c_id` int, `name` varchar(3), `email` varchar(7))
;
INSERT INTO table_1
(`c_id`, `name`, `email`)
VALUES
(1, 'tom', 't@t.com')
;
CREATE TABLE table_2
(`a_id` int, `c_id` int, `address` int, `street` varchar(4))
;
INSERT INTO table_2
(`a_id`, `c_id`, `address`, `street`)
VALUES
(1, 1, 67, 'home'),
(2, 1, 68, 'main')
;
如果您想将sql查询限制为某个人,请说tomWHERE table\u 1.name,比如“tom”
。像这样:
SELECT table_1.name, table_1.email, table_2.address, table_2.street
FROM table_1
JOIN table_2
ON table_1.c_id = table_2.c_id
WHERE table_1.name LIKE 'Tom'
GROUP BY table_1.c_id;
您也可以使用
=
,但使用LIKE可以使用通配符,如T%
表示“只有一条记录”。如何确定应该返回哪一个?分组是我问题的答案。谢谢
select table_1.name as name, table_1.email as email, table_2.address as address, table_2.street as street
from table_1
left join table_2 on table_1.c_id = table_2.c_id