[英]MySQL select from a table and check in another table if the same value exists
[英]mysql check if field value exists in another table
餐桌產品
ProductID | ProductCode | SampleRefNum
1 a1
2 b2
3 c2
表格庫存清單
StockListID | ProductCode | SampleRefNum | QTY
1 a1 10
2 b2 10
3 j100 25
我要2張桌子。 產品表是站點上的當前產品。 庫存清單表是從POS系統上載的清單,其中包含產品及其數量。 產品具有ProductCode或SampleRefNum。
我正在嘗試從產品列表中的所有項目中生成一個列表,這些項目在庫存列表中沒有匹配的ProductCode或SampleRefNum。 在下面的示例中,查詢應返回ProductID 3。
我正在嘗試使用query,而不是在PHP中循環和檢查結果。
嘗試聯接這兩個表,並從STOCK_LIST中獲取ProductCode或SampleRefNum為空的產品
select t1.* from PRODUCTS as t1
left join STOCK_LIST as t2 on t1.ProductID = t2.StockListID
where (t2.ProductCode IS NULL or t2.SampleRefNum is NULL)
您可以使用左聯接來更正結果。
SELECT p.* FROM products AS p
LEFT JOIN stockList AS s
ON p.productID = s.stockListId
OR p.sampleRefNum = s.sampleRefNum;
Select productId from Products where productId NOT IN(Select p.productId From Products p
INNER JOIN Stocklist s ON ( p.ProductCode=s.ProductCode || p.SampleRefNum=s.SampleRefNum));
我想productId和Stocklist Id彼此不相關,它們只是兩個不同表的主鍵。
因此,請嘗試上述查詢。
如果我的猜測是錯誤的,則進行詳細評論。
select table1.id table2.id from table1,table2 where tpl1.id=tpl2.id
在那之后檢查返回數據的num_rows,如果total為0,則表示沒有任何事情
這是正確的答案。 這是@Ye Win和right的權利
SELECT * FROM products AS p
LEFT JOIN stock_list AS s
ON p.ProductCode = s.ProductCode OR p.SampleRefNum = s.SampleRefNum
WHERE (s.ProductCode IS NULL AND p.ProductCode IS NOT NULL OR s.SampleRefNum IS NULL AND p.SampleRefNum IS NOT NULL)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.