开发者

Run MySQL query against every row in a table with PHP

开发者 https://www.devze.com 2023-04-04 13:54 出处:网络
I have limited programming experience, and almost none with PHP. However I\'ve been given a task that requires something more than my basic SQL skills cover... :/

I have limited programming experience, and almost none with PHP. However I've been given a task that requires something more than my basic SQL skills cover... :/

I have a MySQL table ("Users") that contains 334 distinct user IDs, and another table ("Revisions") which contains all the revisions made to a wiki site, along with the ID of the user who committed each revision.

I want to generate a results file (tab delimited) that contains a random sample of 100 revisions for EACH of the users in the开发者_运维问答 "Users" table, along with that user's ID.

My SQL query looks like this:

select r.revision_id, r.revision_timestamp, r.user_id from revision as r, users as u where r.user_id = u.user_id order by rand() limit 100;

As currently written this gives me a random assortment of 100 revisions made by any of the users in the "Users" table. I want 100 random revisions for each user in the table.

I know this can be done with PHP, probably easily, but I don't know the syntax. How can I accomplish this?


Does it have to be a single query? If not, it would be trivial to do an initial query for a list of users, then do a query for each user - the per user query would be identical to your current one, with the addition of where u.user_id = [user id from loop]. As far as syntax, any basic PHP mysql tutorial should give you enough to do the queries, then look at fopen/fwrite/fclose for generating the csv.

Overall pesudocode would look something like:

$file = file open "filename.csv"
$queried_users = mysql query "select u.user_id from users u"

foreach $queried_users as $user
    $entries = mysql query "select r.revision_id, r.revision_timestamp, r.user_id from revision as r, users as u where r.user_id = u.user_id and where u.user_id = " . $user['user_id'] . " order by rand() limit 100;"
    foreach $entries as $entry
        file write to $file $entry['user_id'].','.$entry['revision_id'].','.$entry['revision_timestamp'].'\n';

file close $file

Note that assembling queries by building strings like that is unsafe (better generally to use parameterized queries), but it sounds like this is an internal only thing, so you can probably get away with it here.

0

精彩评论

暂无评论...
验证码 换一张
取 消