簡體   English   中英

從 mysql 中選擇具有引用 id 的行到同一個表

[英]Selecting rows with reference id's to same table from 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]

這個想法是,除了 data_obj 之外,我還有更多常見的列,所以我不想再次插入它們,只想將引用 id 插入到相同的數據中。

是否可以編寫查詢和 select 這個:

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

請注意,我是根據名為 order 的列進行排序的,並且對於引用的行,該列沒有實際數據。

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

其他版本,不返回沒有 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 答案的修改。 此修改使用COALESCE()組合來自主行或引用行的data_obj

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()是一個標准的 SQL function 返回其第一個非 NULL 參數。

你為什么不用一張以上的桌子?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM