Guesser
Guesser

Reputation: 1857

SQL/PHP - Get table name in PHP from UNION

SELECT entry_id,a.about,null title,null article ,null description

FROM about a 

WHERE 
(
MATCH(a.about) AGAINST ('$search' IN BOOLEAN MODE)
)
AND a.user_id='$user_id'

UNION
select entry_id,null, b.title,b.article,b.description
from articles b 

WHERE
(
MATCH(b.title,b.article,b.description) AGAINST ('$search' IN BOOLEAN MODE)
)
AND b.user_id='$user_id'

Is it possible to find out the origin of a result here (which table) in PHP?

So if a match comes from the articles table as opposed to the about table can that information be retrieved in PHP somehow?

Upvotes: 1

Views: 159

Answers (2)

CrazyMenConnected
CrazyMenConnected

Reputation: 702

Add another column on the query to distinguish them. Like this:

SELECT 1 AS Field0, Field1, Field2 from Table_A
UNION 
SELECT 2 AS Field0, Field1, Field2 from Table_B

Rows returned with the Field0 set to 1 are from table A, if it's the value 2 it's from table B

Upvotes: 2

HMagdy
HMagdy

Reputation: 3295

Simply you can use "SQL aliases"

SQL aliases are used to give a database table, or a column in a table, a temporary name.

Basically aliases are created to make column names more readable.

SQL Alias Syntax for Columns

SELECT column_name AS alias_name
FROM table_name;

SQL Alias Syntax for Tables

SELECT column_name(s)
FROM table_name AS alias_name;

Upvotes: 1

Related Questions