【问题标题】:MySQL query eleminating duplicates from second tableMySQL查询从第二个表中删除重复项
【发布时间】:2014-02-12 06:58:26
【问题描述】:

我有两个 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

【问题讨论】:

  • 什么意思是“只有一条记录”。如何确定应该退回哪些?

标签: mysql join


【解决方案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 将确定您要使用哪一列来对结果进行分组。顺便提一句。如果您喜欢更改列标题,您可以添加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;

你也可以使用=,但是你可以使用像T%这样的通配符

【讨论】:

  • GROUP BY 是我的问题的答案。谢谢!
【解决方案2】:

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

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

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

【讨论】:

    【解决方案3】:
    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-16
      • 2017-09-16
      • 1970-01-01
      相关资源
      最近更新 更多