2009-03-05 3 views
0

Ich habe eine Tabelle wie:Zeilen auswählen mit Bezug ids auf derselben Tabelle von MySQL

 
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] 

Die Idee ist, dass ich mehr Spalten andere als data_obj haben, die gemeinsam sein kann, so will ich nicht zu fügen Sie sie erneut ein, möchten Sie nur eine Referenz-ID zu den gleichen Daten einfügen.

Ist es möglich, eine Abfrage zu schreiben und diese wählen:

 
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 

Bitte beachten Sie, dass ich befehle nach Spalte genannten Reihenfolge und es gibt keine aktuellen Daten für diese Spalte für referenzierte Zeilen.

Antwort

1
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 

Andere Version, die Zeilen zurückgeben nicht ohne 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 
+0

Dies funktioniert nicht. Die Zeilen ohne ref_id geben NULL als data_obj zurück. –

+0

Nun, Sie haben nicht angegeben, was Sie wollten. – vartec

0

Hier ist eine Modifikation von @ vartec des answer. Diese Modifikation verwendet COALESCE(), um die data_obj entweder aus der primären Zeile oder der referenzierten Zeile zu kombinieren.

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() ist eine Standard-SQL-Funktion, die ihre erste nicht-NULL Argument zurückgibt.

0

Warum verwenden Sie nicht mehr als eine Tabelle?

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