RawwrBag
RawwrBag

Reputation: 602

MySQL SELECT with conditionally NULL column

I'm brand new to SQL programming, and having a bit of trouble. I have the following MySQL script:

SELECT
    MyPrimaryTable.PrimaryKey, Alias1.String AS Output1,
    CASE
        WHEN Id2 IS NOT NULL THEN Alias2.String
        ELSE ""
    END AS Output2
FROM MyPrimaryTable, MySecondaryTable AS Alias1, MySecondaryTable AS Alias2
WHERE
    MyPrimaryTable.Id1 = Alias1.Id1
    AND ((MyPrimaryTable.Id2 IS NULL) OR (MyPrimaryTable.Id2 = Alias2.Id2));

Basically, I have a primary table that contains two IDs, Id1 and Id2, and I'm trying to associate each one of these IDs with a string in a secondary table and display these strings in the SELECT result. However, the second ID in the primary table is allowed to be NULL. The output I would like, in this case, is the first string as expected and the second string as blank (""). The script I wrote does this, except it adds a new row for each possible string, even though all the rows look the same.

Expected results with possible strings Foo1, Foo2, Foo3, and Foo4, with two entries in the table:

PK   Output1 Output2
1    Foo1    Foo4
2    Foo2

What I get:

1    Foo1    Foo4
2    Foo2
2    Foo2
2    Foo2

How can I clean this up and make it work as expected? Thanks.

EDIT: I was hoping not to use DISTINCT because I want to use this in a VIEW, and DISTINCT will make the view non-updatable.

Upvotes: 0

Views: 1132

Answers (1)

DanielB
DanielB

Reputation: 20230

Try grouping with

GROUP BY MyPrimaryTable.PrimaryKey

on the other end, you may join the tables not with WHERE

SELECT
    MyPrimaryTable.PrimaryKey, 
    Alias1.String AS Output1,
    CASE
        WHEN Id2 IS NOT NULL THEN Alias2.String
        ELSE ""
    END AS Output2
FROM MyPrimaryTable, 
    LEFT JOIN MySecondaryTable AS Alias1 ON MyPrimaryTable.Id1 = Alias1.Id1
    LEFT JOIN MySecondaryTable AS Alias2 ON MyPrimaryTable.Id2 = Alias2.Id2

Upvotes: 1

Related Questions