我正在尝试进行多次数据库选择,其中我有事件和音乐风格(等等)。然而,由于一个事件可以有多种音乐风格,我决定做一个多关系模型。
这就是我创造的:
SELECT
a.* FROM music_types AS a, events_music_types AS b
WHERE
a.id = b.music_type_id
AND
b.event_id = events.ID
并将其插入到我的代码中,现在看起来像这样:
$query =
"SELECT
events.EVENT_NAME, events.start_datetime, events.end_datetime, events.VENUE_LOCATION, events.PARTY_TYPE, events.IMAGE_URL, events.ENTRANCE_PRICE,
venues.VENUE_NAME, venues.BEER_PRICE, venues.WINE_PRICE, SPIRITS_PRICE,
party_types.PARTYTYPE,
a.*
FROM events
INNER JOIN venues
ON events.VENUE_LOCATION = venues.ID
INNER JOIN party_types
ON events.PARTY_TYPE = party_types.ID
INNER JOIN music_styles AS a, events_music_styles AS b
WHERE start_datetime >= '$DATE_START_SELECTED'
AND end_datetime < '$DATE_END_SELECTED'
AND a.id = b.music_style_id
AND b.event_id = events.ID
";
$result = mysql_query($query) or die(mysql_error());
echo "<table border='1'>
<tr>
<th> Poster </th>
<th> Event Name </th>
<th> Venue Name </th>
<th> Party Type </th>
<th> Entrance Price </th>
<th> Music </th>
<th> € of Beer </th>
<th> € of Wine </th>
<th> € of Spirits </th>
</tr>";
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
echo "<tr>";
echo "<td><IMG src='" . $row['IMAGE_URL'] . "'></td>";
echo "<td>" . $row['EVENT_NAME'] . "</td>";
echo "<td>" . $row['VENUE_NAME'] . "</td>";
echo "<td>" . $row['PARTYTYPE'] . "</td>";
echo "<td>" . $row['ENTRANCE_PRICE'] . "</td>";
echo "<td>" . $row['MUSIC_STYLE_NAME'] . "</td>";
echo "<td>" . $row['BEER_PRICE'] . "</td>";
echo "<td>" . $row['WINE_PRICE'] . "</td>";
echo "<td>" . $row['SPIRITS_PRICE'] . "</td>";
echo "</tr>";
}
然而,虽然代码确实获得了一个事件的所有音乐风格,但它并没有将它放入一行,而是将行重复为每个事件的音乐风格的次数。
我如何将它组合成一行并用逗号分隔音乐风格?谢谢:)!
答案 0 :(得分:2)
将您的查询更改为 -
$query =
"SELECT
events.EVENT_NAME,
events.start_datetime,
events.end_datetime,
events.VENUE_LOCATION,
events.PARTY_TYPE,
events.IMAGE_URL,
events.ENTRANCE_PRICE,
venues.VENUE_NAME,
venues.BEER_PRICE,
venues.WINE_PRICE,
SPIRITS_PRICE,
party_types.PARTYTYPE,
GROUP_CONCAT(music_styles.MUSIC_STYLE_NAME) AS MUSIC_STYLE_NAME
FROM events
INNER JOIN venues
ON events.VENUE_LOCATION = venues.ID
INNER JOIN party_types
ON events.PARTY_TYPE = party_types.ID
INNER JOIN events_music_styles
ON events.ID = events_music_styles.event_id
INNER JOIN music_styles
ON events_music_styles.music_style_id = music_styles.id
WHERE start_datetime >= '$DATE_START_SELECTED'
AND end_datetime < '$DATE_END_SELECTED'
GROUP BY events.ID
";
您还有各种各样的连接样式,我现在已经更正了。
答案 1 :(得分:1)
在查询中使用适当的GROUP BY
语句并使用GROUP_CONCAT()
。
答案 2 :(得分:1)
我不知道任何可以直接实现的mysql函数。也许有人可以纠正我。您可以查看CREATE AGGREGATE FUNCTION
,但乍一看文档看起来很混乱。
另一种选择是将它们用PHP分组。首先,您需要将events.ID as eventID
和venues.ID as venueID
添加到SELECT
列表中。然后在while
循环中,您希望将它们组合为关联数组,并为每个$row
添加一个新值以连接音乐风格。在该循环之后,您需要循环遍历新的数据数组,并输出您获得的值。那些相同的将被覆盖,你将有新的,连接的字符串可以调用。
在mysql中创建聚合函数可能会更快,更有效。您需要创建一个接收所有值,连接它们并返回字符串的值。在SELECT
中,它与使用SUM()
或其他内置聚合的方式类似。