![](/img/trans.png)
[英]SQL select rows if a column value is not in a group of a different column's values
[英]SQL select rows with the same column's value
大家下午好! 你可以幫幫我嗎? :)
數據庫示例 :
ID Catalog Code Description Type Supplier Supplier Code
1 6083 TV LG 32 tv lg ud28f1137ka-ga-i2-tr
1 6083 TV LG 32 tv samsung asfb1145-ssd # select it
2 6129 Phone 5X phone apple mics_rp
2 6129 Phone 5X phone htc nco_p13 961-x
2 6129 Phone 5X phone nokia n_41s
3 6210 Friezer agd samsung asfb1145-ssd # found match
it has the same
`Supplier Code`
上面的ID
被分配給Catalog Code
。 除ID
外,所有字段均為VARCHAR
。 可能是空的。
我想做什么:
如果 Supplier Codes
之一相同,則選擇例如Catalog Code = 6083
並獲取所有其他Catalog Codes
。
因此,我應該得到: Catalog Code = 6210
(最后一行),因為它的Supplier Code
與6083
(第一行)相同。
我可憐的嘗試:
SELECT a.*
FROM `TABLE` a
WHERE EXISTS
(SELECT 1
FROM `TABLE` b
WHERE b.`Catalog Code` = '6083'
AND (
a.`Supplier Code` NOT IN ('')
AND a.`Supplier Code` IN b.`Supplier Code`
)
)
需要設計改進
我的實際數據庫有10萬多行 。 我認為數據庫設計需要改進,但是哪些需要改進?
INDEXES
, PRIMARY KEY
,帶外FOREIGN KEY
第二個DB?
我會這樣寫查詢:
select t.*
from t
where t.supplier_code in (select t2.supplier_code
from t t2
where t2.catalog_code = '6083'
);
您的代碼很奇怪。 你為什么not in ('')
? 這是多余的。 然后在第二in
,你需要一個列表,而不是列值。 實際上,只要=
就足夠了。
為了提高性能,您需要在t(catalog_code, supplier_code)
上建立索引。
對於這個特定問題,您如何使用2表。
1)包含目錄代碼詳細信息。(保留目錄代碼作為主鍵)
2)供應商詳細信息(保留ID作為主鍵-1,2,3)
3)目錄代碼和供應商代碼ID映射(兩個表中的外鍵)都為整數值,因此由於比較,查詢將更快。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.