我如何在“多个”中查询多个表?

时间:2018-02-28 11:48:12

标签: sql ms-access

我有三张表与多对多关系

class UpdatePolicyDocumentMockCase(SimpleTestCase):

    IPFS_JSON_MOCK = {"Hash": "mockhash"}

    def setUp(self):
        # some setup before tests

    @patch('apps.utils.ipfs_storage.save_to_ipfs')
    def some_test(self, mock_method):

        mock_method.return_value = self.IPFS_JSON_MOCK
        self.assertEqual(save_to_ipfs("", "", ""), self.IPFS_JSON_MOCK)

三个表中的多对多关系:

CREATE TABLE plate(
   pid integer NOT NULL,
   pname text
);

CREATE TABLE vegetables(
   vid integer NOT NULL,
   vname text
); 

CREATE TABLE meat(
       mid integer NOT NULL,
       mname text
    );

+------+-----+
| pid  | vid |
+------+-----+
|   1  |  13 |
|   1  |  12 |
|   2  |  12 |
+------------+

+-------+---+ | pid |mid| +-------+---+ | 1 | 2 | | 1 | 3 | | 2 | 3 | +-------+---+ 我需要检查:

当用户输入印版的成分时,

示例:

**query**

vid"13","12" 

然后通过检查多对多关系表,查询将检查成分是否可以形成平板。 我尝试使用IN语句,但没有找到结果

任何帮助?

1 个答案:

答案 0 :(得分:0)

我相信你需要找到含有所有肉类的盘子,然后才能找到含有所有蔬菜的盘子。完成后,只需处理JOIN即可获得交叉。

select pid
from
(
  -- plates having all the meats
  select pid
  from platemeat pm
  where pm.mid in (12,13)
  group by pid
  having count(distinct mid) = 2
) t1
join
(
  -- plates having all the vegetables
  select pid
  from plateveget pv
  where pv.vid in (2,3)
  group by pid
  having count(distinct vid) = 2
) t2 on t1.pid = t2.pid