tags:

views:

430

answers:

3

I have a table such as:

id  name  ref_id  order  data_obj
--  ----  ------  -----  --------
1   Sam   0       15     [binary data]
2   Jack  0       20     [binary data]
3   Sue   0       25     [binary data]
4   Sam2  1       -      [no data]
5   Sue2  3       -      [no data]
6   Sam3  1       -      [no data]

The idea is that I have more columns other than data_obj which can be common, so I don't want to insert them again, just want to insert a reference id to the same data.

Is it possible to write a query and select this:

1 - Sam - binary data from id 1
4 - Sam2 - binary data from id 1
6 - Sam3 - binary data from id 1
2 - Jack - binary data from id 2
3 - Sue - binary data from id 3
5 - Sue2 - binary data from id 3

Please note that I'm ordering according to column named order and there's no actual data for this column for referenced rows.

+1  A: 
SELECT t1.id, t1.name, t2.data_obj 
FROM your_table t1
LEFT JOIN your_table t2 ON t1.ref_id = t2.id
ORDER BY t1.order

Other version, which doesn't return rows without ref

SELECT t1.id, t1.name, t2.data_obj 
FROM your_table t1, your_table t2
WHERE t1.ref_id = t2.id
ORDER BY t1.order
vartec
This does not work. The rows with no ref_id return NULL as data_obj.
Well, you didn't specify what you wanted.
vartec
A: 

Here's a modification of @vartec's answer. This modification uses COALESCE() to combine the data_obj from either the primary row or the referenced row.

SELECT t1.id, t1.name, COALESCE(t1.data_obj, t2.data_obj) 
FROM your_table t1
LEFT JOIN your_table t2 ON t1.ref_id = t2.id
ORDER BY COALESCE(t1.order, t2.order), ref_id;

COALESCE() is a standard SQL function that returns its first non-NULL argument.

Bill Karwin
A: 

Why aren't you using more than one table?

CREATE TABLE user (
    user_id number not null (some form of auto increment or sequence),
    name varchar(50) not null,
    otherdata type,
    primary key (id));

CREATE TABLE common (
    common_id number not null (autoinc),
    user_id number not null,
    commondata type,
    primary key (common_id),
    unique index (user_id, common_id));

SELECT u.name, u.otherdata, c.commondata
FROM user u, common c
WHERE u.user_id = c.user_id

TABLE user
user_id  name   otherdata
1        Sam    abc
2        Jack   def
3        Sue    ghi

Table common
common_id user_id  commondata
1         1        AAA
2         1        BBB
3         1        CCC
4         2        DDD
5         3        EEE
6         3        FFF

Output
name   otherdata  commondata
Sam    abc        AAA
Sam    abc        BBB
Sam    abc        CCC
Jack   def        DDD
Sue    ghi        EEE
Sue    ghi        FFF
jmucchiello