简体   繁体   English

从 mysql 中选择具有引用 id 的行到同一个表

[英]Selecting rows with reference id's to same table from mysql

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.这个想法是,除了 data_obj 之外,我还有更多常见的列,所以我不想再次插入它们,只想将引用 id 插入到相同的数据中。

Is it possible to write a query and select this:是否可以编写查询和 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

Please note that I'm ordering according to column named order and there's no actual data for this column for referenced rows.请注意,我是根据名为 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

Other version, which doesn't return rows without ref其他版本,不返回没有 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

Here's a modification of @vartec's answer .这是对@vartec 答案的修改。 This modification uses COALESCE() to combine the data_obj from either the primary row or the referenced row.此修改使用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() is a standard SQL function that returns its first non-NULL argument. COALESCE()是一个标准的 SQL function 返回其第一个非 NULL 参数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM