Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query two tables then output in one column

i want to query two tables then give the result in one column eg

table1

id   name  town 
23   john  nyc
34   mark  ATl
44   ali   Dubs


table2

cno reg
45  kln
47  dsgd
28  wer

the output i expect is

newcolumn
   23
   34
   44
   45
   47
   28
like image 859
dannjoroge Avatar asked Oct 29 '15 11:10

dannjoroge


People also ask

How can I get data from two tables in a single query?

In SQL, to fetch data from multiple tables, the join operator is used. The join operator adds or removes rows in the virtual table that is used by SQL server to process data before the other steps of the query consume the data.

How do I show two columns of data in one column in SQL?

By replacing the existing column using REPLACE() function with CONCAT() function.

How do I join two tables in a column in SQL?

The join is done by the JOIN operator. In the FROM clause, the name of the first table ( product ) is followed by a JOIN keyword then by the name of the second table ( category ). This is then followed by the keyword ON and by the condition for joining the rows from the different tables.


1 Answers

You need to use MySQL UNION.

SELECT id FROM table 1

UNION 

SELECT cno AS id FROM table2

In UNION, you can combine results from two or more database tables.

But, it needs that the selected columns should be similar.

For example, if you are fetching 5 fields from one SQL and 6 fields from another SQL.

And making UNION of these two queries, it will not work.

Above SQL works because, you are selecting one column each from SQLs.

like image 120
Pupil Avatar answered Sep 19 '22 21:09

Pupil