[英]SQL select rows with the same column's value
Good afternoon you everyone! 大家下午好! Could you help me?
你可以帮帮我吗? :)
:)
DATABASE SAMPLE : 数据库示例 :
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`
The above ID
is assigned to Catalog Code
. 上面的
ID
被分配给Catalog Code
。 All fields are VARCHAR
except for ID
. 除
ID
外,所有字段均为VARCHAR
。 Could be empty. 可能是空的。
WHAT I'D LIKE TO DO: 我想做什么:
Select eg Catalog Code = 6083
and get all other Catalog Codes
IF one of Supplier Codes
is the same. 如果
Supplier Codes
之一相同,则选择例如Catalog Code = 6083
并获取所有其他Catalog Codes
。
So I should get: Catalog Code = 6210
(last row) because it has the same Supplier Code
as 6083
(first row). 因此,我应该得到:
Catalog Code = 6210
(最后一行),因为它的Supplier Code
与6083
(第一行)相同。
MY POOR ATTEMPT: 我可怜的尝试:
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`
)
)
NEED FOR DESIGN IMPROVEMENTS 需要设计改进
My real DB has over 100 000 rows . 我的实际数据库有10万多行 。 I feel the DB design needs improvements but which ones?
我认为数据库设计需要改进,但是哪些需要改进?
INDEXES
, PRIMARY KEY
, second DB with FOREIGN KEY
? INDEXES
, PRIMARY KEY
,带外FOREIGN KEY
第二个DB?
I would write the query more like this: 我会这样写查询:
select t.*
from t
where t.supplier_code in (select t2.supplier_code
from t t2
where t2.catalog_code = '6083'
);
Your code is rather strange. 您的代码很奇怪。 Why would you have
not in ('')
? 你为什么
not in ('')
? This is redundant. 这是多余的。 Then on the second
in
, you need a list, not a column value. 然后在第二
in
,你需要一个列表,而不是列值。 In fact, just =
is sufficient. 实际上,只要
=
就足够了。
For performance, you want an index on t(catalog_code, supplier_code)
. 为了提高性能,您需要在
t(catalog_code, supplier_code)
上建立索引。
For this particular question how about you use 2 table . 对于这个特定问题,您如何使用2表。
1) contains catalog code details.(keep catalog code as primary key) 1)包含目录代码详细信息。(保留目录代码作为主键)
2) Supplier details (keep ID as primary key- 1,2,3) 2)供应商详细信息(保留ID作为主键-1,2,3)
3) catalog code and supplier code-ID mapping (foreign key from both tables) .. both are integer values so queries will be bit faster because of comparison. 3)目录代码和供应商代码ID映射(两个表中的外键)都为整数值,因此由于比较,查询将更快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.