[英]Select and join on dynamic table name
I would like to get all information about every item
. 我想获得有关每
item
所有信息。 Items has global variable (here on_stock
), but every item has also its own property in different table, and that table has the same name as the items type name. Items具有全局变量(此处为
on_stock
),但是每个项目在不同的表中也都有其自己的属性,并且该表具有与项目类型名称相同的名称。
name
name
上加入其type_id name
.id name
.id的所选项目 Here is the sample: 这是示例:
[items]
id | on_stock | type_id
-----+----------+-----------
1 1 1(=car)
2 0 1(=car)
3 1 2(=ship)
4 0 2(=ship)
[types]
id | name
----+--------
1 car
2 ship
[car]
id | top_speed
----+-----------
1 200
2 300
[ship]
id | color
-----+-------
3 red
4 blue
expected result: 预期结果:
1 on_stock=1 top_speed=200
2 on_stock=0 top_speed=300
3 on_stock=1 color=red
4 on_stock=0 color=blue
Please help to achieve this! 请帮助实现这一目标!
If I could not do it in one request, I'll do it in more(1+item types count). 如果我不能在一个请求中做到这一点,我将在更多(1个以上的项目类型计数)中做到。
first, I need the required types as array(id=>name): 首先,我需要所需的类型为array(id => name):
$req_types = array();
$rs = mysql_query("
SELECT items.type_id,types.name
FROM items
JOIN types ON items.type_id=type.id
GROUP BY items.type_id
");
while($type= mysql_fetch_assoc($rs))
$req_types[$type['id']] = $type['name'];
then I need the common and individual item data: 那么我需要通用和单个项目数据:
$groups = array();
foreach($req_types as $table)
{
$rs = mysql_query("
SELECT items.*,$table.*
FROM items
JOIN $table ON $table.id=items.id
");
while($item = mysql_fetch_assoc($rs))
$groups[$table][] = $item;
}
It isn't pretty, but neither is the data structure. 它不是很漂亮,但是数据结构也不是。 Here is a query to do what you want
这是一个查询来做你想要的
SELECT I.id, I.On_stock, C.top_speed,S.Color
FROM ITEMS I
LEFT JOIN Car C ON (I.ID = C.CarID)
LEFT JOIN Ship S ON (I.ID = S.ShipID)
You will have to tweak the query every time you add a new item type, but that is just a downside of this data structure. 每次添加新的项目类型时,您都必须调整查询,但这只是该数据结构的缺点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.