Jump to content

Query multiple tables, with same column names


ryanmetzler3

Recommended Posts

I have a DB with 4 tables in it.There is 4 different comment sections on my website, so each table has the same structure, but holds information unique to that comment section. Im trying to query all 4 tables and pull the comments by one specific user from all of them. But the row "comment" is in all 4 tables, it says it is ambiguous and wont work. Is there anyway around this? Or do I have to rename the columns in each table? 

<?php
include $_SERVER['DOCUMENT_ROOT'] . '/comm_1/config.php';

$query= "SELECT comment FROM threaded_comments,threaded_comments2,threaded_comments3,threaded_comments4 WHERE author = '$username'" or die (mysql_error());
			
$result = mysql_query($query) or die (mysql_error());
			while ($row = mysql_fetch_assoc($result)) {
				echo $row['comment'];
			}
?>

If the 4 structures are the same they should be in a single "comments" table with an added "section" column to distinguish them.

 

However, given what you have

SELECT `comment`, 0 as section FROM threaded_comments WHERE author = '$username'
UNION
SELECT `comment`, 1 as section FROM threaded_comments1 WHERE author = '$username'
UNION
SELECT `comment`, 2 as section FROM threaded_comments2 WHERE author = '$username'
UNION
SELECT `comment`, 3 as section FROM threaded_comments3 WHERE author = '$username'

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.