背景:我的雇主有一个由真正旧版本的MySQL(3.23)驱动的数据库。我被要求在数据库中找到重复的序列号和MAC地址。
我能够找到重复的序列号,但由于这个版本的MySQL不支持子查询,我不得不求助于使用临时表。这些是我最终使用的两个SQL语句:
CREATE TEMPORARY TABLE IF NOT EXISTS Inventory_Duplicate_Serials
SELECT Serial
FROM Inventory
WHERE Serial IS NOT NULL
GROUP BY Serial
HAVING COUNT(Serial) > 1
SELECT DeviceName, Model, Inventory.Serial
FROM Inventory
INNER JOIN Inventory_Duplicate_Serials
ON Inventory.Serial = Inventory_Duplicate_Serials.Serial
ORDER BY Serial
现在我需要找到重复的MAC地址。问题是“库存”表有三个MAC地址字段(MAC,MAC2和MAC3)。因此,例如,如果项目的“MAC”字段的值与另一个项目的“MAC2”字段的值相同,我需要知道它。我该怎么做呢?谢谢你的时间。
更新:已解决。我最终创建了两个临时表(Inventory_All_MACs和Inventory_Duplicate_MACs)。这是五个查询:
CREATE TEMPORARY TABLE IF NOT EXISTS Inventory_All_MACs
SELECT MAC
FROM Inventory
WHERE MAC != ''
CREATE TEMPORARY TABLE IF NOT EXISTS Inventory_All_MACs
SELECT MAC2 AS MAC
FROM Inventory
WHERE MAC2 != ''
CREATE TEMPORARY TABLE IF NOT EXISTS Inventory_All_MACs
SELECT MAC3 AS MAC
FROM Inventory
WHERE MAC3 != ''
CREATE TEMPORARY TABLE IF NOT EXISTS Inventory_Duplicate_MACs
SELECT MAC
FROM Inventory_All_MACs
GROUP BY MAC
HAVING COUNT(MAC) > 1
SELECT DeviceName, Model, Inventory_Duplicate_MACs.MAC AS DuplicateMAC, Inventory.MAC, MAC2, MAC3
FROM Inventory_Duplicate_MACs
INNER JOIN Inventory
ON Inventory.MAC = Inventory_Duplicate_MACs.MAC
OR Inventory.MAC2 = Inventory_Duplicate_MACs.MAC
OR Inventory.MAC3 = Inventory_Duplicate_MACs.MAC
ORDER BY Inventory_Duplicate_MACs.MAC, DeviceName, Model
谢谢大家!
答案 0 :(得分:1)
想到一个“简单”的解决方案是创建第二个临时表,列出一列中的所有MAC地址,因此您需要为第一个临时表中的一个条目创建三个条目。
答案 1 :(得分:0)
对这个答案不是100%肯定,但使用LEFT JOINS可能值得尝试,例如:
SELECT address1
FROM addresses
LEFT JOIN Inventory_Duplicate_Addresses ad1
ON Addresses.MAC = ad1.mac
LEFT JOIN Inventory_Duplicate_Addresses ad2
ON Addresses.MAC = ad2.mac2
LEFT JOIN Inventory_Duplicate_Addresses ad3
ON Addresses.MAC = ad3.mac3
答案 2 :(得分:0)
CREATE TEMPORARY TABLE IF NOT EXISTS Inventory_Mac
SELECT Mac
FROM Inventory
INSERT INTO Inventory_Mac
SELECT Mac2
FROM Inventory
INSERT INTO Inventory_Mac
SELECT Mac3
FROM Inventory
CREATE TEMPORARY TABLE IF NOT EXISTS Inventory_Duplicate_Mac
SELECT Mac, COUNT(*) AS cnt
FROM Inventory_Mac
GROUP BY Mac
HAVING COUNT(*) > 1
SELECT DeviceName, Model, im.Mac, i.Mac, i.Mac2, i.Mac3
FROM Inventory_Duplicate_Mac AS im
JOIN Inventory AS i
ON i.Mac = im.Mac
OR i.Mac2 = im.Mac
OR i.Mac3 = im.Mac
ORDER BY im.Mac