Question

Problem: Given two tables: TableA, TableB, where TableA has a one-to-many relationship with TableB, I want to retrieve all records in TableB for where the search criteria matches a certain column in TableB and return NULL for the unique TableA records for the same attribute.

Table Structures:

Table A

ID(Primary Key)      | Name          | City
1                    | ABX           | San Francisco
2                    | ASDF          | Oakland
3                    | FDFD          | New York
4                    | GFGF          | Austin
5                    | GFFFF         | San Francisco

Table B

ATTR_ID              |Attr_Type      | Attr_Name            | Attr_Value
1                    | TableA        | Attr_1               | Attr_Value_1
2                    | TableD        | Attr_1               | Attr_Value_2
1                    | TableA        | Attr_2               | Attr_Value_3
3                    | TableA        | Attr_4               | Attr_Value_4
9                    | TableC        | Attr_2               | Attr_Value_5

Table B holds attribtue names and values and is a common table used across multiple tables. Each table is identified by Attr_Type and ATTR_ID (which maps to the IDs of different tables).
For instance, the record in Table A with ID 1 has two attributes in Table B with Attr_Names: Attr_1 and Attr_2 and so on.

Expected Output

ID                   | Name          | City             | TableB.Attr_Value
1                    | ABX           | San Francisco    | Attr_Value_1
2                    | ASDF          | Oakland          | Attr_Value_2
3                    | FDFD          | New York         | NULL
4                    | GFGF          | Austin           | NULL
5                    | GFFFF         | San Francisco    | NULL

Search Criteria: Get rows from Table B for each record in Table A with ATTR_NAME Attr_1. If a particular TableA record doesn't have Attr_1, return null.

My Query

select id, name, city,
    b.attr_value from table_A
    join table_B b on
    table_A.id =b.attr_id and b.attr_name='Attr_1'
Was it helpful?

Solution

This is a strange data structure. You need a left outer join with the conditions in the on clause:

select a.id, a.name, a.city, b.attr_value
from table_A a left join
     table_B b
     on a.id = b.attr_id and b.attr_name = 'Attr_1' and b.attr_type = 'TableA';

I added the attr_type condition, because that seems logic with this data structure.

OTHER TIPS

I dont have an sql server to test the command, but what you want is an inner/outer join query. You could do something like this

select id, name, city,
    b.attr_value from table_A
    join table_B b on
    table_A.id *= b.attr_id and b.attr_name *= 'Attr_1'

Something like this should do the trick for you

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top