简体   繁体   中英

fetch data from two table with different column numbers and order them based on date

hi every body i have multiple table with different column number in my database. tables do not have any common column name except id and date. and if it is a problem i can change them too. now the problem is i want to fetch rows from this tables and order them by date. i write this code
//table1

1, car1, 2016-07-02 00:00:00,price1,engine1
2, car2, 2016-07-05 00:00:00,price2,engine2
3, car3, 2016-07-07 00:00:00,price3,engine3
4, car4, 2016-07-08 00:00:00,price4,engine4

//table2

1, home1, 2016-07-03 00:00:00
2, home2, 2016-07-06 00:00:00
3, home3, 2016-07-09 00:00:00

//result

1, car1, 2016-07-02 00:00:00,price1,engine1
2, home1, 2016-07-03 00:00:00,,
3, car2, 2016-07-05 00:00:00,price2,engine
4, home2, 2016-07-06 00:00:00,,
5, car3, 2016-07-07 00:00:00,price3,engine3
6, car4, 2016-07-08 00:00:00,price4,engine4
7, home3, 2016-07-09 00:00:00,,

i wrote this code but it is not working well

 <?php error_reporting(0); $mysqli=NEW MySQLI("localhost","root","","database"); mysqli_query($mysqli,"SET NAMES 'utf8'"); mysqli_query($mysqli,"SET character_set_connection='utf8'"); $resultset= $mysqli->query("SELECT table1.*,table2.* FROM table1 JOIN table2"); echo $resultset->num_rows; ?> 

please help thank you

I don't know your column names but this should do it:

select column_car, column_date, column_price, column_engine from table1
union
select column_home as column_car, column_date, NULL as column_price, NULL as column_engine from table2

In the second select I am aliasing NULL as the price and engine so that both selects would have the same result set .

When using union both select statements must have the same column names and type.

You can specify where clauses in each select or a global where, depending on your needs :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM