获取MySQL中的行,这些行在另一个表

时间:2016-06-27 11:56:19

标签: mysql sql

有两个表格,详情如下所述:

表1:

+-------------+---------------+
 | user_id     |  isactive     |
 +-------------+---------------+
 | aaa         | 0             |
 +-------------+---------------+
 | bbb         | 0             | 
 +-------------+---------------+ 

表2:

 +-------------+---------------+-----------+
 |store_no     |  owner        | store     |
 +-------------+---------------+-----------+
 |1234         | aaa           | aaa,xyz   |
 +-------------+---------------+-----------+
 |1006         | aaa           | aaa       | 
 +-------------+---------------+-----------+
 |1005         | ccc           | www       | 
 +-------------+---------------+-----------+

我需要从表1中获取行,这些行的条目既不在表2的“所有者”列中也不在“存储”列中。例如,在上面的场景中,结果集应该包含“bbb”。 我尝试使用find_in_set,找到等但无法根据需要获取详细信息。请帮忙..

更新了表格格式

查询:

select a.user_id from table1 u
left outer join table2 a
on (owner=user_id or concat(',',store,',') like concat('%,',user_id,',%'))
where (find_in_set(user_id,owner) = 0 or find_in_set(user_id,store) = 0)
and  isactive=0

仅供参考,商店列可以包含多个用户标识的连接值

3 个答案:

答案 0 :(得分:1)

您可以尝试使用NOT EXISTS

SELECT 
T1.user_id
FROM TABLE_1 T1
WHERE NOT EXISTS (
    SELECT 1 
      FROM 
    TABLE_2 T2
    WHERE T2.owner = T1.user_id OR FIND_IN_SET(T1.user_id,T2.store) > 0
);

SQL FIDDLE DEMO

建议:

Is storing a delimited list in a database column really that bad?

答案 1 :(得分:0)

你可以这样做: -

SELECT * FROM table1 WHERE user_id NOT IN (SELECT owner FROM table2) AND NOT FIND_IN_SET(user_id, (SELECT store FROM table2));

第二个选项: -

SELECT * FROM table1 WHERE user_id NOT IN (SELECT owner FROM table2) AND FIND_IN_SET(user_id, (SELECT store FROM table2)) = 0;

它可能对你有帮助。

答案 2 :(得分:0)

我认为这应该有效:

int