2

我有一个数据库表,我需要验证用户是否输入了相同或部分相同的信息。

这就是我的想法

数据库布局

rec_id (pk), user_id,
name, phone, address_1, address_2, zip, 
company, co_phone, co_address_1, co_address_2, co_zip, 
billing, bi_phone, bi_address_1, bi_address_2, bi_zip

查询

SELECT rec_id 
FROM tbl_name
WHERE user_id = '123456789'
OR '1112223333' IN (phone, co_phone, bi_phone)
OR 'John Doe' IN (name, business, billing)
OR '12345' IN (zip, co_zip, bi_zip)
OR '123 main street' IN (address_1, co_address_1, bi_address_1)
OR 'po box 123' IN (address_2, co_address_2, bi_address_2)

如果任何数据匹配(是的,这将是误报),我需要旧的 rec_id。

想知道是否有更好的方法来做到这一点?

谢谢

4

1 回答 1

2

要使此查询正常执行,您将需要为要测试的每个列使用单独的索引。所有列上的组合索引对于 OR 条件根本没有帮助(如果你有 AND,它会有所帮助)。

但是,我想无论您添加哪些索引,您的查询都会导致全表扫描。您可能想尝试使用 UNIONs 而不是 OR 来查看是否会有所不同:

SELECT rec_id FROM tbl_name WHERE tax_id = '123456789'
UNION
SELECT rec_id FROM tbl_name WHERE phone = '1112223333'
UNION
SELECT rec_id FROM tbl_name WHERE co_phone = '1112223333'
UNION
SELECT rec_id FROM tbl_name WHERE bi_phone = '1112223333'
UNION
SELECT rec_id FROM tbl_name WHERE name = 'John Doe'
UNION
SELECT rec_id FROM tbl_name WHERE business = 'John Doe'
UNION
SELECT rec_id FROM tbl_name WHERE billing = 'John Doe'
UNION
-- etc...

像这样重写它的想法是,现在每个子查询都可以使用索引(当然假设您已经添加了必要的索引)。

于 2011-01-19T21:42:08.777 回答