我在一个MySQL数据库中有三个表:
stores_id)
“商店”表对每个企业都有一行。join_stores_states表将单个业务链接到其所在的每个州。因此,一些企业在3个州都有商店,所以它们在join_stores_states中有3行,而其他企业在1个州有商店,所以在join_stores_states中只有1行。
我正在试图找出如何编写一个查询,该查询将在一行中列出每个业务,但仍然显示它所处的所有状态。
下面是我到目前为止所得到的,它显然给了我join_stores_states之外的每一行:
SELECT states.*, stores.*, join_stores_states.*
FROM join_stores_states
JOIN stores
ON join_stores_states.stores_id=stores.stores_id
JOIN states
ON join_stores_states.states_id=states.states_id粗略地说,这就是它给我的东西:
alabama
这是我更想看到的:
关于尝试哪种查询方法的建议将与工作查询一样受到欢迎。
发布于 2012-01-10 17:27:54
如果您需要将状态列表作为字符串,则可以使用MySQL的GROUP_CONCAT函数(或者,如果您使用的是另一种SQL方言),如下面的示例所示。如果您想单独对状态进行任何类型的进一步处理,我希望您像以前一样运行查询,然后通过迭代生成的行,将结果集收集到一个更复杂的结构中(作为最简单的度量,数组的哈希表,但更复杂的OO设计当然是可能的)。
SELECT stores.name,
GROUP_CONCAT(states.name ORDER BY states.name ASC SEPARATOR ', ') AS state_names
FROM join_stores_states
JOIN stores
ON join_stores_states.stores_id=stores.stores_id
JOIN states
ON join_stores_states.states_id=states.states_id
GROUP BY stores.name此外,即使您只需要连接字符串,而不需要数据结构,一些数据库可能没有聚合连接函数,在这种情况下,您将不得不进行客户端处理。在伪代码中,因为您也没有指定一种语言:
perform query
stores = empty hash
for each row from query results:
get the store object from the hash by name
if the name isn't in the hash:
put an empty store object into the hash under the name
add the state name to the store object's stores arrayhttps://stackoverflow.com/questions/8807547
复制相似问题