简体   繁体   中英

Fetching records from different tables in the database

My application has a facebook-like stream that displays updates of various types. So it will show regular posts (from the "posts" table), and events (from the "events" tables) table and so on.

The problem is I have no idea how to fetch these records from different tables since they have different columns. Shall I query the database multiple times and then organize the data in PHP? if so, how? I'm not sure how I should approach this.

Your help is much appreciated :)

Ideally you'd simply use a JOIN to obtain data from multiple tables in one query. However, without knowing more about your table schemas it's hard to provide any useful specifics. (It most likely won't be possible unless you've factored this in from the beginning that said.)

As such, you might also want to create a generic "meta" table that provides information for each of the posts/events in a common format, and provides a means to link to the relevant table. (ie: It would contain the "parent" type and ID.) You could then use this meta table as the source for the "updates" stream and drill down to the approriate content as required.

Unless the events and post are related to each other, then you'd probably query them separately, even if they show up on the same page.

You're not going to want to use JOIN just for the sake of it. Only if there is a foreign key relationship. If you don't know what that is, then you don't have one.

If the data tables are related to each other you can generally get the data back in a single query using some combination of JOINs and UNIONs. For a better answer, however, you'll have to post the structure of your data tables and a sample of what (combined) records you need for the website.

If you don't know the columns, you can get the table meta-data and find out what the columns represent and their corresponding data types.
If you know which columns, you can select from the multiple tables or even use nested selects or joins to get the data out.

Join the tables on user_id ie

Select * from posts p
left join status_updates su on p.user_id = su.user_id
limit 25;

or if your tables differ too much then play with a temporary table first

create table tmp_updates
(
 select user_id, p.id as update_id, 'post' as update_type, p.text from posts;
);

insert into table tmp_updates
(
 select user_id, su.id as update_id, 'status' as update_type, su.text from status_updates;
);

Select * from tmp_updates
where user_id = '...'
limit 25;

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