我该如何编写这个MySQL查询?

时间:2010-05-17 03:05:30

标签: sql database-design mysql

我正在使用灯堆工作资产数据库。

在此示例中,请考虑以下5个表:

资产, 服务器, 笔记本电脑, 桌面, 软件

所有表都有一个id的主键,这是一个唯一的资产ID。

每个对象都具有所有资产属性,然后根据资产类型在相应的表中具有其他属性。如果类型是服务器,台式机或笔记本电脑,它也有软件表中的项目。

以下是表创建语句:

// connect to mysql server and database "asset_db"
mysql_connect("localhost", "asset_db", "asset_db") or die(mysql_error());
mysql_select_db("asset_db") or die(mysql_error());

// create asset table
mysql_query("CREATE TABLE asset(
id VARCHAR(50) PRIMARY KEY, 
company VARCHAR(50), 
location VARCHAR(50),
purchase_date VARCHAR(50),
purchase_order VARCHAR(50),
value VARCHAR(50),
type VARCHAR(50),
notes VARCHAR(200))")
or die(mysql_error());  
echo "Asset Table Created.</br />";

// create software table
mysql_query("CREATE TABLE software(
id VARCHAR(50) PRIMARY KEY, 
software VARCHAR(50),
license VARCHAR(50))")
or die(mysql_error());  
echo "Software Table Created.</br />";

// create laptop table
mysql_query("CREATE TABLE laptop(
id VARCHAR(50) PRIMARY KEY, 
manufacturer VARCHAR(50),
model VARCHAR(50),
serial_number VARCHAR(50),
esc VARCHAR(50),
user VARCHAR(50),
prev_user VARCHAR(50),
warranty VARCHAR(50))")
or die(mysql_error());  
echo "Laptop Table Created.</br />";

// create desktop table
mysql_query("CREATE TABLE desktop(
id VARCHAR(50) PRIMARY KEY, 
manufacturer VARCHAR(50),
model VARCHAR(50),
serial_number VARCHAR(50),
esc VARCHAR(50),
user VARCHAR(50),
prev_user VARCHAR(50),
warranty VARCHAR(50))")
or die(mysql_error());  
echo "Desktop Table Created.</br />";

// create server table
mysql_query("CREATE TABLE server(
id VARCHAR(50) PRIMARY KEY, 
manufacturer VARCHAR(50), 
model VARCHAR(50),
warranty VARCHAR(50))")
or die(mysql_error());
echo "Server Table Created.</br />";

?>

如何查询数据库,以便在按ID搜索时,我会收到该资产ID的所有相关字段?

谢谢。

1 个答案:

答案 0 :(得分:2)

SELECT asset.id
    ,asset.company
    ,asset.location
    -- ,... Any more columns from asset
    ,software.software
    ,software.license
    ,laptop.model AS laptop_model
    ,desktop.model AS desktop_model
    -- etc.
    ,COALESCE(laptop.model, server.model, desktop.model) AS model -- assumes only one non-NULL
FROM asset
LEFT JOIN software
    ON software.id = asset.id
LEFT JOIN laptop
    ON laptop.id = asset.id
LEFT JOIN desktop
    ON desktop.id = asset.id
LEFT JOIN server
    ON server.id = asset.id
WHERE asset.id = <your_id>