【问题标题】:MySQL Match sku in two tables, and return specific rowsMySQL 在两个表中匹配 sku,并返回特定行
【发布时间】:2016-05-11 14:47:04
【问题描述】:

所以我有两张表,如下所述。我正在尝试制作一个查询,该查询将与 table_2 中的 sku 与 table_1 中的 sku 匹配,并在匹配时返回 table_1 中的相应图像和 table_2 中的相应标题。

table_1

id  sku     title       images
=============================================
1   11-001  The_title   image-link/11-001.jpg
2   11-002  The_Title   image-link/11-002.jpg
3   11-001  The_Title   image-link/11-001.jpg

table_2

id  sku     title       images
========================================================
1   11-001  The_title   some-other-image-link/11-001.jpg
2   11-002  The_Title   some-other-image-link/11-002.jpg
3   11-001  The_Title   some-other-image-link/11-001.jpg

所需的输出如下所示:

id  sku     title               images
======================================================
1   11-001  Title-From_Table2   image-link-from-table1
2   11-002  Title-From_Table2   image-link-from-table1
3   11-001  Title-From_Table2   image-link-from-table1

我尝试了几种不同的连接和方法,但都没有获得所需的输出。任何帮助或方向将不胜感激。谢谢!

【问题讨论】:

    标签: mysql sql database join


    【解决方案1】:

    是 sku 字段上的标准内部联接。

    select f.id, f.sku, s.title, f.images
    from table_1 f
    inner join table_2 s on
    s.sku = f.sku
    

    请注意,要仅返回一个 id,您需要选择返回哪一个,因为 table_1 的 id 可能与 table_2 的 id 不同。


    如果您不需要最终重复,请在最后添加一个 group by

    select f.id, f.sku, s.title, f.images
    from table_1 f
    inner join table_2 s on
    s.sku = f.sku
    group by f.id, f.sku, s.title, f.images
    

    【讨论】:

      【解决方案2】:

      从描述看来,你只需要加入 SKU 并获得select t1.id, t1.sku, t2.title, t1.images

      select t1.id, t1.sku, t2.title, t1.images
      from table_1 t1, table_2 t2
      where t1.sku = t2.sku
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-04-18
        • 2023-03-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多