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 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私