0

我有三个 XREF 表。

  1. order_delivery_xref: order_id (int), delivery_id (int)
  2. delivery_invoice_xref: delivery_id (int), invoice_id (int)
  3. invoice_order_xref: invoice_id (int), order_id (int)

我现在需要将它们组合成一个公用表,如下所示:

order_delivery_invoice_xref: order_id (int), delivery_id (int), invoice_id (int)

有没有办法使用查询来做到这一点?还是程序?还是使用 php 脚本 + mysql 查询?

笔记:

  1. delivery_id总是与order_id
  2. Aninvoice_id并不总是存在,并且需要null在行中,如果缺少

这是我尝试过的:

SELECT order_id, delivery_id
FROM order_delivery_xref
WHERE 1

...等等所有三个表。

然后我为第一个数组运行一个foreach()循环,检查其他数组的使用函数(替换where ),并在 html 中创建一个 table>tr>td。phpisset()NULL!isset()

我不太确定这是否是正确的方法。有人可以提出更好的方法吗?

4

1 回答 1

0

It depends on what you want to do. To do it once, this will work:

create table odx (order_id int, delivery_id int); create table dix (delivery_id int, invoice_id int); create table iox (invoice_id int, order_id int);

insert into odx values (1, 11), (2, 22), (3,33); insert into dix values (22, 333), (22, 444), (33, 555); insert into iox values (333, 1), (444, 2), (555, 2);

create table odix (order_id int, delivery_id int, invoice_id int);

insert into odix (order_id, delivery_id, invoice_id) select odx.order_id, odx.delivery_id, dix.invoice_id from odx left join dix on dix.delivery_id = odx.delivery_id left join iox on iox.order_id = odx.order_id;

But you have to make your own decisions about how to join the tables - because of the contents of the three tables, you can join them many ways with different results.

Also, you have to figure out what to do when any of the subsidiary tables changes - do you recreate the odix table from scratch or just add new or changed records.

You'll find that doing as much of this as possible in MySQL will be faster than in PHP - MySQL is very good at joining tables together and aggregating data in this way.

Finally, you probably want to think about why you are doing this - why put the data in another table. With MySQL, you can always assemble the data together to view them this way, so copying the data doesn't seem to make sense. It creates redundancy in your database, which can get confusing and difficult to manage.

Check out a few references on "normalization" to get some ideas.

于 2012-12-01T12:52:28.787 回答