SQL加入多个条件

时间:2016-06-10 09:06:55

标签: mysql sql sql-server

我有一项艰巨的任务是建立一个从类似下面的表中检索的数组:

表-A

id  | scenario_id | entity_id
1     1;2;3;4;5     1;3
2     4;5;8;10      2;3
3     1;5;8;11      1;2;4;
4     3;5;8;9       4;5;

现在,如果一个用户从一个entity_id中选择,假设为3,那么SQL查询应返回类似于:

的内容
scenario_id
1;2;3;4;5;8;10

或者,如果他选择5,则返回的数组应如下所示:

scenario_id
3;5;8;9

这可以仅使用SQL语句吗?

4 个答案:

答案 0 :(得分:1)

你可以使用这样的东西在scenario_id中找到一个id,但它总是一个FULL TABLE扫描。

SELECT *
FROM table_a
WHERE
 FIND_IN_SET('3', REPLACE(scenario_id,';',',')) > 0;

答案 1 :(得分:1)

对于SQL Server,您可以使用它来获得所需的输出:

DECLARE @xml xml, @entity_id int = 3
--Here I generate data similar to yours
;WITH cte AS (
SELECT *
FROM (VALUES
(1, '1;2;3;4;5', '1;3'),
(2, '4;5;8;10', '2;3'),
(3, '1;5;8;11', '1;2;4;'),
(4, '3;5;8;9', '4;5;')
) as t(id, scenario_id, [entity_id])
)
--create xml
SELECT @xml = (
SELECT CAST('<i id="'+ CAST(id as nvarchar(10)) +'"><s>' + REPLACE(scenario_id,';','</s><s>') + '</s><e>' + REPLACE([entity_id],';','</e><e>') + '</e></i>' as xml)
FROM cte
FOR XML PATH('')
)
--Normalizing the table and getting result
SELECT STUFF((
SELECT ';' + CAST(scenario_id as nvarchar(10))
FROM (
    SELECT DISTINCT t.v.value('.','int') as scenario_id
    FROM @xml.nodes('/i/s') as t(v)
    INNER JOIN  @xml.nodes('/i/e') as s(r)
        ON t.v.value('../@id','int') =  s.r.value('../@id','int')
    WHERE s.r.value('.','int') = @entity_id
) as p
FOR XML PATH('')),1,1,'') as scenario_id

entity_id = 3的输出:

scenario_id
1;2;3;4;5;8;10

entity_id = 5

scenario_id
3;5;8;9

答案 2 :(得分:0)

简单。正常化您的架构......在最粗糙的情况下,可能如下......

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id  INT NOT NULL
,scenario_id INT NOT NULL
,entity_id INT NOT NULL
,PRIMARY KEY (id,scenario_id,entity_id)
);

INSERT INTO my_table VALUES
(1, 1,1),
(1, 1,3),
(1, 2,1),
(1, 2,3),
(1, 3,1),
(1, 3,3),
(1, 4,1),
(1, 4,3),
(1, 5,1),
(1, 5,3),
(2, 4,2),
(2, 4,3),
(2, 5,2),
(2, 5,3),
(2, 8,2),
(2, 8,3),
(2,10,2),
(2,10,3),
(3, 1,1),
(3, 1,2),
(3, 1,4),
(3, 5,1),
(3, 5,2),
(3, 5,4),
(3, 8,1),
(3, 8,2),
(3, 8,4),
(3,11,1),
(3,11,2),
(3,11,4),
(4, 3,4),
(4, 3,5),
(4, 5,4),
(4, 5,5),
(4, 8,4),
(4, 8,5),
(4, 9,4),
(4, 9,5);

SELECT DISTINCT scenario_id FROM my_table WHERE entity_id = 3 ORDER BY scenario_id;
+-------------+
| scenario_id |
+-------------+
|           1 |
|           2 |
|           3 |
|           4 |
|           5 |
|           8 |
|          10 |
+-------------+

答案 3 :(得分:0)

将scenario_id拆分为';'并复制到临时表以使用它为您的查询使用instr和substring函数 这个link可能对您有所帮助,但您需要一个循环函数来将您的过程称为';'重复

相关问题