0

I have a ticket system I set up for multiple websites. Each table in the database is the same on all website.

My question is how would I query the multiple tables from each database?

Example:

  • I have 5 tickets open in database dogs
  • I have 2 tickets open in database cats

I need to write a query that will tell me what is the most recent ticket submitted.

So I want to know where the ticket came from and the time it was posted.

Here is what I have tried but need some guidance as I've never worked with multiple databases before.

$database_1 = 'dogs';
$database_2 = 'cats';

$recent = DB::getInstance()->query("
SELECT `st_id`,`dates`,`complex` FROM {$database_1}.`support_ticket` WHERE `status` = 'OPEN' ORDER BY `dates` DESC LIMIT 1
UNION ALL
SELECT `st_id`,`dates`,`complex` FROM {$database_2}.`support_ticket` WHERE `status` = 'OPEN' ORDER BY `dates` DESC LIMIT 1 ");

foreach($recent->results() as $r):
?>
<div class="box-bottom">Most Recent: <?php echo escape($r->complex); ?> - 
<?php echo escape (date("F d, Y - h:i a", strtotime ($r->dates))); ?></div>
<?php endforeach ?>
1
  • Never-mind this works SELECT st_id,dates,complex` FROM {$database_1}.support_ticket UNION ALL SELECT st_id,dates,complex FROM {$database_2}.support_ticket WHERE status = 'OPEN' ORDER BY dates DESC LIMIT 1 "); ` Commented Oct 2, 2014 at 19:08

1 Answer 1

1

Just use one ORDER BY statement

SELECT `st_id`,`dates`,`complex` 
FROM {$database_1}.`support_ticket` 
WHERE `status` = 'OPEN' 
UNION ALL
SELECT `st_id`,`dates`,`complex` 
FROM {$database_2}.`support_ticket` 
WHERE `status` = 'OPEN' 
ORDER BY `dates` DESC LIMIT 1 
Sign up to request clarification or add additional context in comments.

5 Comments

yea that works, just tried it after I finished writting the question. Thanks for the help though! =)
do you know of a better way to Select from each table. This doesn't work, but Something like this: SELECT whatever FROM dogs AND cats.support_ticket....etc
Actually started to write a JOIN query, but that doesn't make sense. This is the best way to do this as you now have it without refactoring the database to have all support tickets in one database distinguished by a column containing 'cats' or 'dogs'. That is probably how I would have done it when designing the database.
Yeah I should of planned a little more, but now I'm in to deep to change the databases around. I could, but would take forever. Thanks again for the help.
Yeah. I know what you mean. We have all been there before.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.