Sorting multiple tables MYSQL DateStamp

家住魔仙堡 提交于 2020-01-04 23:27:30

问题


I'm building a simple sell&buy-site and want to list the latest ads on the first pages. In my database I have 4 tables. USERS , CARS, ELECTRONICS and COMPUTERS.

Each of the three tables of items (CARS, ELECTRONICS and COMPUTERS) have DATESTAMP in them, but I can't manage to easily sort them after this DATESTAMP using MySQL and PHP.

They all contain different columns but have DATESTAMP and SSN (identifying the user how owns the ad) in common.

EDIT:

I've tried Joining the tables, sorting them using strtotime in php.. but I can't seem to get the syntax to play along. Played with this code.. but It got very complicated and I was hoping I could do it easier in pure SQL.It's not complete but.. you can see what I was thinking..

 <?php

   mysql_connect("localhost","root","");
   mysql_select_db("project");
   $SSN = utf8_decode(strip_tags($_GET['ssn'])); 

   //firstname,lastname, email, phone, address, zipcode, district
   $result = mysql_query("SELECT * 
                            FROM CARS 
                           WHERE CARS.SSN = '$SSN'");

   $result2 = mysql_query("SELECT * 
                             FROM ELECTRONICS 
                            WHERE ELECTRONICS s.SSN = '$SSN'");

   if (!$result) {
     echo 'Could not run query: ' . mysql_error();
     exit;
   }

   while($obj = mysql_fetch_object($result)) {
     $arr[] = $obj;
   }

   echo '{"users":'.json_encode($arr).'}';

   if (!$result2) {
     echo 'Could not run query: ' . mysql_error();
     exit;
   }

   while($obj = mysql_fetch_object($result2)) {
     $arr[] = $obj;
   }

   echo '{"users":'.json_encode($arr).'}';

   function mysort($a, $b) { 
     return(strtotime($b['datePosted']) - strtotime($a['datePosted'])); 
   } 

   // pre-sort: 
   echo "<pre>Before:\n"; 
   print_r($arr); 
   // do the sort: 
   usort($arr, 'mysort'); 
   // show the result: 
   echo "After:\n"; 
   print_r($arr); 
   echo "</pre>"; 
?>

回答1:


From a design standpoint, you could have an ITEMS table that contains attributes that relate to all types of item, for example ID, DATESTAMP, SSN. Have ID PKs on each of the other item-related tables that match the ID of the relevant item from the ITEMS table.

ITEMS

ID  DATESTAMP  SSN
1   2011-01-01 12345
2   2011-01-02 12345
3   2011-01-04 54321

CARS

ID MANUFACTURER MODEL 
1  Volvo        V40
3  Volkswagen   Beetle

COMPUTERS

ID BRAND PROCESSOR
2  Dell  386


来源:https://stackoverflow.com/questions/5998896/sorting-multiple-tables-mysql-datestamp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!