MySQL查询消除了第二个表中的重复项

时间:2014-02-11 22:32:58

标签: mysql join

我有两个mysql表:table_1和table_2。

TABLE_1:

| c_id | name |  email  |
|  1   | tom  | t@t.com |

TABLE_2:

| a_id | c_id | address | street |
|  1   |  1   |   67    |  home  |
|  2   |  1   |   68    |  main  |

如何创建将选择table_1.name,table_1.email,table_2.address和table_2.street的mysql查询,只返回一条记录,如:

| name | email   | address | street |
| tom  | t@t.com | 67      | home   |

感谢您的任何建议。 问候,T

3 个答案:

答案 0 :(得分:1)

试试这个:

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

SQLfiddle demo

GROUP BY将决定您要使用哪一列对结果进行分组。 B.T.W.如果您希望更改列标题,则可以添加AS,后跟列标题名称(table_1.name AS "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查询限制为某个人说tom WHERE table_1.name LIKE '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%

等通配符

答案 1 :(得分:0)

你应该使用SQL语句LEFT JOIN,例如

SELECT name, email, address, street
FROM table1
LEFT JOIN table2
ON table1.c_id=table2.c_id;

使用可能的选项WHERE name ='tom'

答案 2 :(得分:0)

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