MySQL自关联表

MySQL自关联表,第1张

create table node_tree( id int not null auto_increment primary key, node_name varchar(128) not null default '', up_node_id int, node_level char(1) )ENGINE=InnoDB default charset=utf8 collate=utf8_swedish_ci

insert into node_tree(node_name,up_node_id,node_level) values('jx',null,'1'),('jx.webserver',1,'2'),('jx.webserver.nginx1', 2, '3'), ('jx.logserver', 1, '2')

select

node_tree1.id as 主表ID,

node_tree1.name as 主表名字,

node_tree2.name as 从表名字,

node_tree2.up_id as 从表上级ID

from node_tree1, node_tree2

where node_tree1.name='jx'

select

node_tree1.id as 主表ID,

node_tree1.node_name as 主表名字,

node_tree2.node_name as 从表名字,

node_tree2.up_node_id as 从表上级ID

from node_tree as node_tree1, node_tree as node_tree2

where node_tree1.node_name='jx'

现在的数据库基本都是关系数据库,表与表之间的关联一般都是靠字段来维持的。

例如3个表,分别是用户信息表,购物订单表,帐户金额明细表

表结构如下(我写简单哈):

用户信息表字段:userid,username,password

购物订单表字段:orderid,userid,goods,price

帐户金额明细表:aid,userid,orderid,price

从上面3个表就能看出,他们之间的管理是:

通过用户信心表的userid可以获得购物订单表的订单信息,如果想要获得用户或者购物订单的账户金额明细数据,可使用userid或者orderid去帐户金额明细表查询相关数据,示例SQL如下:

SELECT * FROM 购物订单表字段 where userid=12

SELECT * FROM 帐户金额明细表 where userid=12

SELECT * FROM 帐户金额明细表 where orderid=3356

如果你还不明白的话,可发消息给我。

数据库多表关联,一般采用外键比较方便,也可以额外建一个连接表做多表关联的连接,但这样稍微有点儿复杂,这些是建表方面的关联。查询关联,可以采用多表查询的方式关联查询,这点要求稍高点儿,但关联后再 *** 作单表时,别的表不用受太大的影响,这点特好。


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/9987900.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-04
下一篇 2023-05-04

发表评论

登录后才能评论

评论列表(0条)

保存