我是sql的新手。已经编程了一段时间但总是找到一种不使用数据库的方法。我知道愚蠢。
我对一对多的SQL查询有疑问。
我正在建立一个网站,以便我可以更多地了解数据库。所以我拥有的是一个包含2个表的数据库。一个保存用户信息并保存该用户的硬件。只有一个用户,但该用户可以有多个硬件。我可以编写查询来显示用户信息没问题。我似乎无法理解的是如何编写查询以将所有硬件与该用户相关联并显示它。
这是我的表格示例
用户表
user_id ------ primary key
first_name
last_name
硬件表
hardware_id ---- primary key
serial
model
type
user_id ---- foreign key (link to the user table)
例如
用户表
user_id first_name last_name
01 John Doe
02 Jane Doe
hardware table
hardware_id serial model type user_id
01 cac21 Dell Desktop 01
02 cac22 HP Laptop 01
03 cac24 Apple Laptop 02
任何帮助都会很棒。
由于 GG
答案 0 :(得分:1)
从数据库中查询数据将在每条记录上重复该人的姓名,但在生成页面时,由您决定输出只显示一次名称,然后显示该人的所有硬件,然后转移到下一个人和他们所有的硬件。
所以,使用php,你将拥有一个嵌套循环。外循环用于跟踪每个新人,内循环仅显示该人的记录。保留该人的“身份证”,以防止有一个以上的“John Doe”人实际上是不同的人。身份证将确保适当的单身人士。
现在,查询。连接显示表之间的关系,并且所有引用多个表的查询应始终使用tableAlias.columnName来防止任何歧义。表名别名也是缩短查询可读性的好方法。
select
u.user_id,
u.first_name,
u.last_name,
h.hardware_id,
h.serial,
h.model,
h.type
from
user u <-- the "u" is the alias to user table...
JOIN hardware h <-- "h" is the alias for hardware table
on u.user_id = h.user_id
order by
u.first_name,
u.last_name,
u.user_id
注意我按姓氏,名字按字母顺序排列列表,但后面也包括user_id,所以如果有任何多个“John Doe”用户,那么同样的John Doe#1 vs John Doe#2就是一个单独的记录块。
在你的PHP中(因为我不做PHP,这是伪代码)
获取结果集
nCurrentUserID = 0 (to prepare before the loop)
start loop with first record
if nCurrentUserID is different than current record "User ID"
start new output line and include the name in output as needed
nCurrentUserID = current record "user ID"
end if
while on the same record, now you can output the hardware
fields to your output list
advance to the next record in the result set
end the loop of all records
请务必关闭所有基于html的表格/行/明细标签
答案 1 :(得分:0)
试试这个
SELECT users.firstname,
users.lastname,
hardware.serial
hardware.model
hardware.type FROM users LEFT JOIN hardware ON users.user_id=hardware.user_id