这个MySQL查询的任何问题

时间:2013-01-23 22:07:42

标签: mysql csv

我有这个问题:

   SELECT A.id FROM TableB B
   LEFT JOIN TableA A ON 
          CONCAT(',',B.class_id,',') LIKE CONCAT('%,',A.class_id,',%')
   WHERE A.class_id is not null

表A

 [id]   |   [class_id]
---------------------
 One       1, 10, 16, 18
 Two       14, 11
 Three     19, 13, 15
 Four      10 

表B

 [id]   |   [class_id]
---------------------
 ABC         1
 AC          1
 DE          10 
 DEC         19
 ACD         16
 BCD         18
 BCO         18

我没有从TableA获得TableB中id的所有class_id。我也欢迎任何其他更好的查询建议。

这就是我想要的:

  One   // class_id contains  1, 10 16 and 18 that are in `TableB` class_id
  Three // class_id contains 19 which is in `TableB` class_id
  Four  // class_id contains 10 which is in `TableB` class_id

4 个答案:

答案 0 :(得分:2)

虽然你可能会让这个策略起作用,但它会很棘手且查询速度很慢。麻烦将出现在csv列表开头或结尾的数字,因此与模式'%,X,%'不匹配

你应该做的是制作一个每个(id,class_id)有一行的正确表格,如下所示:

[id]   |   [class_id]
---------------------
One       1
One       10
One       16
One       18
Two       14
Two       11
Three     19
Three     13
Three     15
Four      10

然后您的查询变为普通联接:

SELECT A.id, B.class_id FROM TableB B
join TableA A ON 
      B.class_id = A.class_id
where A.class_id is not null

答案 1 :(得分:1)

这应该有效(编辑):

select A.id from TableA A where A.id not in (
SELECT distinct A2.id FROM TableA A2 where 
    not exists (select B.id from TableB B where CONCAT(',',B.class_id,',') 
                         like CONCAT('%,',A2.class_id,',%')))

答案 2 :(得分:1)

看起来你只是混淆了搜索字符串:

CONCAT(', ',B.class_id,',') LIKE CONCAT('%, ',A.class_id,',%')

应该是

CONCAT(', ',A.class_id,',') LIKE CONCAT('%, ',B.class_id,',%')

因为您正在寻找A中B的出现。

此外,在连接它们时,请注意冒号后的空格

答案 3 :(得分:1)

SELECT a.id, b.class_id
FROM TableA a, TableB b
WHERE CONCAT(', ',a.class_id,', ') LIKE CONCAT('%, ',b.class_id,', %');

您实际上不需要a.class_id is not null ...因为b.class_id中的字符串不在a.class_id中。

SQL Fiddle