MySQL:选择连接的行,其中孩子不属于特定的父母ID

时间:2019-03-22 17:03:40

标签: mysql join left-join right-join

这个问题听起来可能有些混乱,我会尽力进行解释。我有4张桌子:

  • store_item :产品
  • store_cat :产品类别。每个产品都有1个类别。
  • store_cat_attribute :类别属性。每个类别都有N个属性。
  • store_item_stock :按属性分类的商品库存

目标是从import * as updater from './updater'; import { repeatMe } from './code'; test('repeatMe', async () => { jest.useFakeTimers(); let doAsyncStuff = jest.spyOn(updater, 'doAsyncStuff'); doAsyncStuff.mockResolvedValue(true); repeatMe(); jest.advanceTimersByTime(5000); expect(doAsyncStuff).toHaveBeenCalledTimes(1); // Success! await Promise.resolve(); // let callbacks in PromiseJobs run jest.advanceTimersByTime(5000); expect(doAsyncStuff).toHaveBeenCalledTimes(2); // Success! await Promise.resolve(); // let callbacks in PromiseJobs run jest.advanceTimersByTime(5000); expect(doAsyncStuff).toHaveBeenCalledTimes(3); // Success! // ... and so on ... }); 表中获取特定产品的所有{strong> ,只要id不是 链接到当前的store_item_stock

以下是结构的SQLfiddle:my answer here

我当前的查询实际上获取了产品的所有store_item_stock.id_attribute行,但是它还包括属于当前store_item.id_cat的属性:

store_item_stock

例如,store_item.id_cat 2、3和4属于SELECT store_item_stock.id, store_item_stock.id_attribute, store_item_stock.stock FROM store_item_stock LEFT JOIN store_item ON store_item.id_item = store_item_stock.id_item LEFT JOIN store_cat_attribute ON store_cat_attribute.id_cat = store_item.id_cat WHERE store_item_stock.id_item = 1 AND store_item.id_cat = 2 GROUP BY store_item_stock.id 2,而id_attribute 33和34属于id_cat 4,因此如果查询的目的是获取所有id_attribute行,除了将id_cat链接到store_item_stock 2的行之外,应返回:

  • id :104, id_attribute :33,库存:26
  • id :105, id_attribute :34,库存:28

1 个答案:

答案 0 :(得分:1)

SELECT store_item_stock.id, store_item_stock.id_attribute, store_item_stock.stock 
FROM store_item_stock 
JOIN store_cat_attribute 
ON store_item_stock.id_attribute=store_cat_attribute.id_attribute
WHERE id_cat NOT IN (
SELECT store_item.id_cat 
FROM store_item JOIN store_cat_attribute 
ON store_item.id_cat=store_cat_attribute.id_cat 
WHERE store_item.id_cat=2 
GROUP BY store_item.id_cat);

我想这不是那么简单,但是让我们尝试一下,看看条件是否符合您想要的输出。