1

我在数据库中有两张表,一张是 交易表:

id    mac            timestamp     siteid


1     C8BCC8BD7684   1365987620      5


2     8C2DAA4CB9E6   1365995414      4

另一个是设备详细信息表:

id       mac_address       organization 


1        00:00:0E          Fujitsu limited


2        00:00:00          Xerox corporation


3        C8:BC:C8          Apple, inc.


4        8C:2D:AA:         Apple, inc.

我需要加入这两个表。所以输出表应该是这样的,

 id   mac            timestamp     siteid      organization

1     C8BCC8BD7684   1365987620      5         Apple, inc.


2     8C2DAA4CB9E6   1365995414      4         Apple, inc.

我可以使用 wordwrap(substr( transactions.mac, 0, 6),2,":",true) 之类的东西从 transactions.mac 中检索前 6 个字母吗?我已经尝试了下面的代码,但是我得到了 mysql 错误:

"SELECT transactions.mac,equipment_details.mac_address,equipment_details.organization FROM `transactions`, `equipment_details` WHERE transactions.mac LIKE equipment_details.mac_address+'%' "

非常感谢任何帮助!

4

4 回答 4

2
SELECT  a.*,
        b.Organization
FROM    transactions a
        INNER JOIN equipment_details b
            ON SUBSTRING(a.mac, 1,6) = REPLACE(b.mac_address, ':', '')

输出

╔════╦══════════════╦════════════╦════════╦══════════════╗
║ ID ║     MAC      ║ TIMESTAMP  ║ SITEID ║ ORGANIZATION ║
╠════╬══════════════╬════════════╬════════╬══════════════╣
║  1 ║ C8BCC8BD7684 ║ 1365987620 ║      5 ║ Apple, inc.  ║
║  2 ║ 8C2DAA4CB9E6 ║ 1365995414 ║      4 ║ Apple, inc.  ║
╚════╩══════════════╩════════════╩════════╩══════════════╝

这个唯一的问题是它不使用索引,如果你有大型数据库,它的执行速度会很慢。您可以做的最好的方法是正确规范化表格:)

于 2013-05-27T04:49:16.383 回答
1

像这样试试

SELECT transactions.mac,equipment_details.mac_address,equipment_details.organization
FROM `transactions`
JOIN 'equipment_details'
ON equipment_details.mac_address = REPLACE(SUBSTRING('transactions.mac',6),":","")

您现在不需要 like 语句...如果您想与 LIKE 进行比较,那么它的语法应该是

WHERE transactions.mac LIKE equipment_details.mac_address = 'my_string%'
于 2013-05-27T04:32:51.110 回答
0

这个怎么样?

SELECT tr.mac,ed.mac_address,ed.organization
FROM `transactions` tr
JOIN 'equipment_details' ed
ON ed.mac_address = REPLACE(SUBSTRING('tr.mac',6),":","")  

使用替换,您可以直接比较带有“:”的mac地址和没有“:”的mac地址

希望它有帮助。

于 2013-05-27T04:41:06.890 回答
0

你也可以试试这个。内连接可以帮助您连接两个表。我猜您的主键在两个表中都是“id”,并且您在 device_details 表中引用了“id”作为外键。

select tr.id,tr.mac,tr.timestamp,tr.siteid,ed.organisation from transactions tr inner join equipment_details ed ON ed.mac_address = SUBSTRING('transactions.mac',6) where tr.id = ed.id 
于 2013-05-27T04:46:10.297 回答