简体   繁体   中英

MySQL query to retrieve data from multiple tables as nested tree

Found similar questions on SO, but nothing that helped. Here's my problem:

I have a table, 'events', that will be rather large. Also there are these two tables: 'photos' and 'videos'. Every 'events' record has an eid (event id). Every 'photos' and 'videos' record has an aeid (associated event id).

To grab event data of say 20 events, I'm currently running PHP like so:

array = get top 20 events
for these 20 events
  array['photos'] = get all photos
  array['videos'] = get all videos
return events array

I'm finding out that this is running too slow. Probably because that equates to 41 mysql queries. I realize I need use JOIN somehow (I think I do at least), but I can't figure our how to structure my query so that it nested the photos and videos in the same way that I'm doing it in the pseudocode above. Also, I don't think I have the time to spare to switch over to postgres (unless it is very highly suggested); I'm working with a large enough codebase for that to be a headache with only one dev (me).

I'm willing to read documents/manuals if you post them. But, I've already done so in a few places to no avail. Thanks!

Try something like..

 SELECT E.eid, V.aeid, P.aeid 
 FROM events E, videos V, photos P 
 WHERE E.eid='$ID' and V.aeid='$ID' and P.aeid='$ID' 
 ORDER BY E.eid desc

Untested, but you should get the point

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM