获取TableA id,其中TableB id等于具有字符串的TableA列

时间:2016-11-25 09:35:00

标签: mysql

我有两个表TableA和TableB。

表A:

id | users        |
-------------------
1  | ["2","5","4"]|
2  | NULL         |
3  | ["5"]        |

表B

id | Name |
-----------
2  | Jane |
3  | Joe  |
4  | John |
5  | Jack |

如何获得一个结果来显示TableA id在TableA用户中的TableA id?

  • 所以Jane = 1
  • for Joe = Null
  • for John = 1
  • 和杰克= 1,3

2 个答案:

答案 0 :(得分:0)

这样的事情应该有效:

SELECT b.id,
       b.Name,
       COALESCE(a.id, 'NA') AS a_id
FROM TableB b
LEFT JOIN TableA a
    ON FIND_IN_SET(b.id, REPLACE(REPLACE(REPLACE(a.users, '[', ''), ']', ''), '"', '')) > 0

在这里演示:

SQLFiddle

答案 1 :(得分:0)

我有一个表(i)的整数(0-9)(也是我)......

我并没有认真地提倡这个解决方案,只是为了好玩......

DROP TABLE IF EXISTS table_a;
DROP TABLE IF EXISTS table_b;

CREATE TABLE table_a
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,users VARCHAR(100) NULL
);

INSERT INTO table_a VALUES
(1,'["2","5","4"]'),
(2,NULL),
(3,'["5"]');

CREATE TABLE table_b
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,name VARCHAR(12) NOT NULL
);

INSERT INTO table_b VALUES
(2,'Jane'),
(3,'Joe'),
(4,'John'),
(5,'Jack');

SELECT b.name
     , GROUP_CONCAT(a.id ORDER BY a.id+0) ids
  FROM table_b b
  LEFT
  JOIN 
     ( SELECT DISTINCT a.id, SUBSTRING_INDEX(SUBSTRING_INDEX(
                       REPLACE(
                         REPLACE(
                           REPLACE(a.users,'"','')
                           ,'[','')
                           ,']','')                       
                       ,',',i.i+1)
                       ,',',-1)
                       x 
                  FROM 
                 table_a a,ints i
      ) a
     ON a.x = b.id
  GROUP
     BY name;

 +------+------+
 | name | ids  |
 +------+------+
 | Jack | 1,3  |
 | Jane | 1    |
 | Joe  | NULL |
 | John | 1    |
 +------+------+