我如何从多选中选择行的索引

时间:2019-09-06 08:45:02

标签: mysql

如何导出查询..?

创建表查询:

CREATE TABLE `account_list` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `nick` char(12) NOT NULL DEFAULT '',
  `sponsor` char(12) DEFAULT '',
  PRIMARY KEY (`id`),
  UNIQUE KEY `nick` (`nick`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;

表格数据示例:

ID      NICK    SPONSOR
1       A       NULL
2       B       C
3       C       NULL
4       D       C
SELECT a.id, a.nick,b.sponsor
FROM account_list a (select b.sponsor from account_list b)

然后,我想要这样的东西:

SELECT id, nick, sponsor FROM `account_list` ....

ID      NICK    SPONSOR
1       A       
2       B       3
3       C       
4       D       3

查看赞助商行。
打印的C为3。

我该如何选择像这样?

2 个答案:

答案 0 :(得分:0)

您可以尝试使用account_list进行左加入

SELECT a.id, a.nick, b.id sponsor
from  account_list a 
left join account_list b ON b.nick = a.sponsor 

答案 1 :(得分:0)

您的查询几乎是正确的(我认为)子查询where子句应引用昵称

drop table if exists t;
create table t
(ID  int,    NICK varchar(1),   SPONSOR varchar(1));
insert into t values
(1    ,   'A'    ,   NULL),
(2    ,   'B'    ,   'C'),
(3    ,   'C'    ,   NULL),
(4    ,   'D'    ,   'C');

SELECT id, nick,sponsor,
       (select b.id 
        from t as b 
        WHERE a.sponsor= b.nick and a.sponsor is not null
          )
FROM t as a
; 

+------+------+---------+--------------------------------------------------------------------------------------------------+
|    1 | A    | NULL    |                                                                                             NULL |
|    2 | B    | C       |                                                                                                3 |
|    3 | C    | NULL    |                                                                                             NULL |
|    4 | D    | C       |                                                                                                3 |
+------+------+---------+--------------------------------------------------------------------------------------------------+
4 rows in set (0.00 sec)