logiacer logiacer - 26 days ago 5
SQL Question

Define which type select union mysql php

SELECT column1, column2, column3, column4, column5 FROM table1 WHERE column2 = :value
UNION SELECT column1, column2, column3, column4, column5 FROM table2 WHERE column2 = :value


So I have this query and here's my php:

http://pastebin.com/XQ6G81sQ

Now as you see
<td><?= $infor->method ?></td>


I would like to show here If it is from table1 or table2, how would I do that?

Answer

@bassxzero's answer will work if you really are looking for all results from Table1 and Table2 regardless of if all columns(1,2,3...) are the same between the table as adding adding the table values into its column list makes them unique. though you should use UNION ALL not UNION in that case because that is what you are doing.

If there can be exact duplicates of values for columns(1,2,3...) between Table1 and Table2 but you only want to display them as 1 row then you could use a pattern like this:

SELECT
    CASE
       WHEN SUM(FromTable) > 2 THEN 'Both Tables'
       WHEN SUM(FromTable) = 2 THEN 'Table2'
       ELSE 'Table1'
    END as FromTable
    ,column1, column2, ...
FROM
    (
       SELECT 1 as FromTable, column1, column2, ...
       FROM
          Table1
       WHERE
          column2 = :value

       UNION ALL

       SELECT 2, column1, column2, ...
       FROM
          Table2
       WHERE
          column2 = :value
    ) t
GROUP BY
    column1, column2, ....