How to join two tables with one of them not having a primary key and not the same character length

后端 未结 1 463
清酒与你
清酒与你 2021-01-28 00:28

I am dealing with two tables: \"dyndomrun.ddid\" = with a Primary key and \"domainregion.domainid\" = without any primary key nor foreign key

相关标签:
1条回答
  • 2021-01-28 01:10

    Try this to compare the first 8 characters only:

    SELECT r.domainid, r.dombegin, r.domend, d.ddid 
    FROM   domainregion r
    JOIN   dyndomrun d ON r.domainid::varchar(8) = d.ddid 
    ORDER  BY r.domainid, d.ddid, r.dombegin, r.domend;
    

    The cast implicitly trims trailing characters. ddid only has 8 characters to begin with. No need to process it, too. This achieves the same:

    JOIN   dyndomrun d ON left(r.domainid, 8) = d.ddid 
    

    However, be advised that the string function left() was only introduced with PostgreSQL 9.1. In earlier versions you can substitute:

    JOIN   dyndomrun d ON substr(r.domainid, 1, 8) = d.ddid
    

    __

    Basic explanation for beginners:

    • The query uses a JOIN. Read more about that in the manual.

    • FROM domainregion r is short for FROM domainregion AS r. AS is just noise in this case in PostgreSQL. The table alias makes the query shorter and easier to read but has no other impact in here. You can also use table aliases to include the same table multiple times for instance.

    • The join condition ON r.domainid::varchar(8) = d.ddid joins only those rows together where the two expressions match exactly. Again, read about those basics in the manual (or any other source).

    It's a simple query, not much to explain here.

    0 讨论(0)
提交回复
热议问题