Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql SQL查询一列上的多个条件(在同一个表上)_Mysql_Sql_Join - Fatal编程技术网

Mysql SQL查询一列上的多个条件(在同一个表上)

Mysql SQL查询一列上的多个条件(在同一个表上),mysql,sql,join,Mysql,Sql,Join,我有以下问题,这里是一个更好理解的例子 假设我有一张这样的桌子: 我想从Spec列中获取具有Spec 2而不具有Spec 5的不同ID(不是null) 预期结果如下: 预期结果: 是不是有点像左撇子? 不幸的是,我没有通过查询得到所需的结果。使用存在和不存在 select camid from table_name t1 where not exists ( select 1 from table_name t2 where t1.camid=t2.camid

我有以下问题,这里是一个更好理解的例子

假设我有一张这样的桌子:

我想从Spec列中获取具有Spec 2而不具有Spec 5的不同ID(不是null)

预期结果如下:

预期结果:

是不是有点像左撇子?
不幸的是,我没有通过查询得到所需的结果。

使用存在和不存在

select camid from table_name t1
where not exists ( select 1 from table_name t2 where t1.camid=t2.camid
                   and Specs= 'Spec 5')
 and exists ( select 1 from table_name t2 where t1.camid=t2.camid 
                                   and Specs= 'Spec 2')
试试下面的脚本-

SELECT DISTINCT Cam_ID 
FROM your_table
WHERE Cam_ID NOT IN
(
    SELECT DISTINCT Cam_ID 
    FROM your_table
    WHERE Specs = 'Specs 5'
)
AND Specs = 'Specs 2'
AND Cam_ID IS NOT NULL

下面的SQL脚本应该为您提供所需的输出

SELECT CamId FROM (
SELECT t.CamId,
STUFF((
SELECT  ',' + Specs FROM
(SELECT t1.Specs FROM test_table as t1 
WHERE t1.CamId = t.CamId) AS T 
FOR XML PATH('')
),1,1,'') AS specs
FROM test_table AS t
WHERE CamId IS NOT NULL
GROUP BY CamId) AS t5
where t5.specs LIKE '%Specs 2%'
AND t5.specs NOT LIKE '%Specs 5%'

你们有家长表吗?因为这看起来像一个子表(Cam ID是Repeat)。如果有任何父表,则可以从内部联接提取查询结果
SELECT CamId FROM (
SELECT t.CamId,
STUFF((
SELECT  ',' + Specs FROM
(SELECT t1.Specs FROM test_table as t1 
WHERE t1.CamId = t.CamId) AS T 
FOR XML PATH('')
),1,1,'') AS specs
FROM test_table AS t
WHERE CamId IS NOT NULL
GROUP BY CamId) AS t5
where t5.specs LIKE '%Specs 2%'
AND t5.specs NOT LIKE '%Specs 5%'
SELECT Cam_Id 
FROM table_one t1 
WHERE
    NOT EXISTS ( SELECT 1 FROM table_one t2 WHERE t1.Cam_Id = t2.Cam_Id AND Specs = 'Spec 5' ) 
    AND EXISTS ( SELECT 1 FROM table_one t2 WHERE t1.Cam_Id = t2.Cam_Id AND Specs = 'Spec 2' ) 
GROUP BY Cam_Id