简体   繁体   中英

SQL Store different types of objects in a single table

I am trying to define a database schema to store a list of "objects" in a table.

The main problem is that I need to have a list of geometric shapes and other kinds of markers in a table, in order to draw them on to a google map.

For example, a circle will have only x,y and radius. A polyline will have a set of points, and a square will have...etc etc...

My first thought was to create 2 related tables like:

object

  • id
  • Name

object_details

  • id
  • object_id (foreign from object)
  • attribute_type ( enum cartesian_point, size etc....)
  • numeric_attribute_valueA
  • numeric_attribute_valueB
  • datetime_attribute_value
  • etc...

But this is a really ugly and inefficent implementation because I may need to have even more different attribute data types - like text or time or anything else and this will complicate the schema creating mostly empty rows in the object_details table.

What would be a good/clean solution for this?

Update:

Reading this question after almost 5 years I'd strongly suggest to consider any Schema-Less database for this kind of problems.

我建议看一下MySQL空间扩展和postgresql的POSTGIS扩展,它们都支持在空间列中存储多种类型的几何图形。

You'll have to pack the data in some format, store it, and unpack it later for use. For example, JSON, which is supported by both PHP and JS. For example in PHP:

$shape = array("kind"=>"circle", "cx"=>45,"cy"=>90,"r"=>20);
$json = json_encode($shape, JSON_NUMERIC_CHECK); // NUMERIC_CHECK doesn't treat numbers as strings

SQL:

$query = "INSERT into SHAPES set `shape`=>'$json'";

You can get back to a PHP array with "json_decode();"

$shape = json_decode($json);

Also, this format makes it easy to use with ajax and jquery, as your server can deliver the JSON contents directly:

$.getJSON("server.php",function(response) {
   console.log("Kind is " + response.kind + ", radius is " + response.r);
});

If you want to avoid using the spatial extensions, you could consider using a text column and populate it with a GEOJSON object. It looks like Google maps can consume GeoJSON , so that might work for you.

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