MYSQL WHERE条件中的多个ID检查

时间:2013-04-25 05:40:05

标签: mysql oracle

我有一个查询,只有在WHERE子句

中所有ID匹配时才需要获取一行

这是查询

SELECT CompanyId
FROM vendors
WHERE VendorId
IN (
'306145244', '1011073437'
)

我希望所有CompanyId同时包含vendorId'306145244'和'1011073437'

如果其中一个VendorId匹配,我不希望companyId。 VendorId应该匹配

分组时我需要2行,如下所示

company Id   Vendor Id
1             306145244
1             1011073437
2             306145244
2             306145244

如果可能,我想在ORACLE

中查询此查询

5 个答案:

答案 0 :(得分:2)

SELECT  CompanyId
FROM    vendors
WHERE   VendorId IN ('306145244', '1011073437')
GROUP   BY CompanyId
HAVING  COUNT(*) = 2

其他链接:


如果vendorID对于每个CompanyId都不唯一,则DISTINCT关键字只需计算唯一值,

SELECT  CompanyId
FROM    vendors
WHERE   VendorId IN ('306145244', '1011073437')
GROUP   BY CompanyId
HAVING  COUNT(DISTINCT VendorId) = 2

答案 1 :(得分:0)

您可能需要查看ALL。

SELECT CompanyId
FROM vendors
WHERE VendorId = ALL (
    query to get numbers.
)

http://dev.mysql.com/doc/refman/5.5/en/all-subqueries.html

答案 2 :(得分:0)

SELECT `CompanyId` , count( `CompanyId` )
FROM `vendors`
WHERE VendorId
IN (
'306145244', '1011073437'
)
GROUP BY `CompanyId`
HAVING count( `CompanyId` ) = 2;

使用此功能,这对我有用并经过测试。

答案 3 :(得分:0)

SQL Server我们可以做的是:

SELECT CompanyId
FROM vendors
WHERE VendorId
IN ('306145244')
intersect
SELECT CompanyId
FROM vendors
WHERE VendorId
IN ('1011073437')

MYSQL不支持intersect。因此,我们必须接近 alternative to intersect in MYSQL

select distinct CompanyId
FROM vendors
where vendorId IN ('306145244')
and CompanyId IN
(SELECT CompanyId
FROM vendors
WHERE VendorId
IN ('1011073437'))

修改

select  CompanyId,VendorId
FROM vendors
where vendorId IN ('306145244')
and CompanyId IN
(SELECT CompanyId
FROM vendors
WHERE VendorId
IN ('1011073437'))
union
select  CompanyId,VendorId
FROM vendors
where vendorId IN ('1011073437')
and CompanyId IN
(SELECT CompanyId
FROM vendors
WHERE VendorId
IN ('306145244'))

<强> SQL Fiddle

答案 4 :(得分:0)

试试这个:

SELECT CompanyId,VendorId
FROM vendors
WHERE VendorId
IN (
select VendorId from vendors
)
order by CompanyId asc;

希望它会对你有所帮助。