查询多对多给我零结果

时间:2018-11-18 01:59:54

标签: mysql

我正在处理此表

tbl公司

|idcompany |   name   |
|   1      |   apple  |
|   2      |    ms    |
|   3      |   pepsi  |

tbl供应商

| idbrand  |   vName   |
|    1     | comp soft |
|    2     |   food    |
|    3     |Electronics|

tbl vendorXcompany

| idbrand  | idcompany |
|    1     |      1    |
|    2     |      3    |
|    1     |      2    |
|    3     |      2    |

我需要知道哪些公司属于电子和计算机软件

在这种情况下应该是

1-毫秒

此查询不返回任何结果

SELECT * FROM company c
JOIN vendorXcompany vc ON c.idcompany = vc.idcompany
JOIN vendor v ON vc.idbrand = v.idbrand
WHERE vc.idbrand = 1 and vc.idbrand = 3

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

您的WHERE条件排除了所有行,因为vc.idbrand = 1vc.idbrand = 3不能一次都为真。您需要做的是通过对符合以下条件之一的行进行计数,找到同时符合条件的公司:

SELECT c.idcompany, c.name
FROM company c
JOIN vendorXcompany vc ON c.idcompany = vc.idcompany
JOIN vendor v ON vc.idbrand = v.idbrand
WHERE vc.idbrand = 1 OR vc.idbrand = 3
GROUP BY c.idcompany
HAVING COUNT(*) = 2

输出:

idcompany   name
2           ms

SQLFiddle demo