【问题标题】:result of selection is array and I want to use it to "where in" another selection选择的结果是数组,我想用它来“在哪里”另一个选择
【发布时间】:2017-07-19 23:07:52
【问题描述】:

我有两张桌子(t1 & t2):

t1(第二列是数组)

name  | code        

ee    | 123, 124, 125

ef    | 121, 123    
______________________

t2

code_id | code_desc

121     | xxxxx        

123     | yyyyyyy      

124     | xxxxxxxx   

如果我执行此查询,一切正常:

SELECT * FROM t2 where code_id in (121,122)

但如果我执行此查询,我会得到 NULL 单元格/结果

SELECT * FROM t2 where code_id in (SELECT code FROM t1 where name = ee)

如何从一个查询中获取两个表中的所有信息?

这里是代码,找不到好的sql在线工具

CREATE TABLE t1 (name VARCHAR(200), codes VARCHAR(200));
CREATE TABLE t2 (codes_id VARCHAR(200), codes_desc VARCHAR(200));

INSERT INTO t1 (name, codes) VALUES ('ee', '123,124,125');
INSERT INTO t1 (name, codes) VALUES ('ef', '121,124');
INSERT INTO t1 (name, codes) VALUES ('eh', '123,124,125');
INSERT INTO t2 (codes_id, codes_desc) VALUES ('121', 'yyyyyyyyy');
INSERT INTO t2 (codes_id, codes_desc) VALUES ('122', 'xxxxxxxxx');
INSERT INTO t2 (codes_id, codes_desc) VALUES ('123', 'zzzzzzzzzzz');



SELECT * FROM t2 where code_id in (121,122)
SELECT * FROM t2 where code_id in (SELECT codes FROM t1 where name = 'ee')

【问题讨论】:

    标签: mysql sql arrays selection where-in


    【解决方案1】:

    你可以使用find_in_set函数:

    select *
    from t2
    where exists (
            select 1
            from t1
            where name = 'ee'
            and find_in_set(t2.code_id, t1.code) > 0
            )
    

    不过,我会建议您规范化您的表结构。因为即使上面的查询有效,它也不是sargable

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多