从mysql中检索满足IN子句中所有值的记录

时间:2013-06-05 11:56:18

标签: mysql sql

I have a query:
SELECT
ZIPSECvc255Zip,ZIPSECCODIServiceType
FROM towSearch_ZIP_ZipCodesSecondary
WHERE   ZIPSECCOMlAPAssignee = 57055
AND ZIPSECCODlAPStatus = 302
    AND ZIPSECCODIServiceType in (263,1012)
    AND ZIPSECADDIKey = 314105

I am getting follow result:
ZIPSECvc255Zip  ZIPSECCODIServiceType
  17001               263
  17003               1012
  17007               1012
  17003               263

我只想要17003的单个记录,因为它与ZIPSECCODIServiceType(即263,1012)相关。如何使用查询实现这一目标?

4 个答案:

答案 0 :(得分:0)

这应该

SELECT ZIPSECvc255Zip FROM  
(SELECT ZIPSECvc255Zip, count(*) AS cnt
   FROM towSearch_ZIP_ZipCodesSecondary
  WHERE   ZIPSECCOMlAPAssignee = 57055
    AND ZIPSECCODlAPStatus = 302
    AND ZIPSECCODIServiceType in (263,1012)
    AND ZIPSECADDIKey = 314105
  GROUP BY ZIPSECvc255Zip)
WHERE CNT = 2

你会想要用你想要的任意数量的替换来代替数字2,如果它们改变了(即你的IN条件中有多少个数字)。

答案 1 :(得分:0)

SELECT ZIPSECvc255Zip,ZIPSECCODIServiceType
FROM towSearch_ZIP_ZipCodesSecondary
WHERE   ZIPSECCOMlAPAssignee = 57055
AND ZIPSECCODlAPStatus = 302
AND ZIPSECCODIServiceType = 263 and 
ZIPSECvc255Zip in
   (
     select ZIPSECvc255Zip FROM towSearch_ZIP_ZipCodesSecondary
      WHERE   ZIPSECCOMlAPAssignee = 57055
      AND ZIPSECCODlAPStatus = 302
       AND ZIPSECCODIServiceType = 1012
       AND ZIPSECADDIKey = 314105
   )
AND ZIPSECADDIKey = 314105

答案 2 :(得分:0)

我希望这会有所帮助。

SELECT
ZIPSECvc255Zip,ZIPSECCODIServiceType
FROM towSearch_ZIP_ZipCodesSecondary
WHERE  rowid = (SELECT max(rowid) FROM towSearch_ZIP_ZipCodesSecondary WHERE ZIPSECCOMlAPAssignee = 57055 AND ZIPSECCODlAPStatus = 302 
AND ZIPSECCODIServiceType in (263,1012)
AND ZIPSECADDIKey = 314105 GROUP BY count(ZIPSECvc255Zip)>1)

答案 3 :(得分:0)

SELECT DISTINCT
t1.ZIPSECvc255Zip,t1.ZIPSECCODIServiceType
FROM towSearch_ZIP_ZipCodesSecondary as t1 INNER JOIN towSearch_ZIP_ZipCodesSecondary as t2
ON (t1.ZIPSECvc255Zip = t2.ZIPSECvc255Zip AND t1.ZIPSECCODIServiceType = '263' AND t2.ZIPSECCODIServiceType = '1012')
WHERE   
t1.ZIPSECCOMlAPAssignee = 57055
AND 
t1.ZIPSECCODlAPStatus = 302
AND 
t1.ZIPSECADDIKey = 314105

http://sqlfiddle.com/#!2/325ba/9