douhui9631 2016-11-10 13:53
浏览 146
已采纳

MySQL连接查询,但如果它是重复的,则不显示第一个表的结果

So basically I have 2 tables:

table1

id| name
1   Test
2   Something
3   More

table2

id| table1_id
1   1
2   1
3   1
4   2
5   2
6   3

Now I need the result to be like this:

name      | table2.id
Test        1
            2
            3
Something   4
            5
More        6

So basically no duplicate entries from the first table. So the exact same results as joining it but without showing the name more than once. Is this possible in MySQL or should I just filter it in PHP? I know it's possible in PHP but I am wondering if something like this is achievable in MySQL if so, I'd like to know what to look for. I was thinking something with DISTINCT and/or a left or right join.

  • 写回答

6条回答 默认 最新

  • douzhai1182 2016-11-10 14:38
    关注

    So, you asked if it is possible with MySQL and I answered in comments that it is. If your question was how can I accomplish this with only MySQL, here it is:

    SELECT
    tmp.name,
    tbl2.id
    FROM
        tbl2
    LEFT JOIN (
    SELECT
        tbl2.id AS id,
        tbl1.`name` AS name
    FROM
        tbl2
    INNER JOIN tbl1 ON tbl1.id = tbl2.tbl1_id
    GROUP BY
        tbl2.tbl1_id
    ) AS tmp ON tbl2.id = tmp.id;
    

    Hope it is what you wanted.

    As @roberto06 suggested, this query returns NULL instead of duplicates, but if you don't like NULLs and want an empty string you can change SELECT tmp.name to SELECT IFNULL(tmp.name,'')

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测