在两个表之间组合数据并加入某个列

时间:2014-12-09 01:41:10

标签: php mysql

我有两个表,分别是tbl_product1和tbl_product2。

tbl_product1:

model_name
lot_num
status_prod1
datecreated
date_received

tbl_product2:

model_name
lot_num
status_prod2
last_date

我想在这两个表和lot_num之间以及一列中组合model_name。然后从tbl_prod1和status_prod2,last_date加入status_prod1,datecreated,date_received。

我的SQL查询:

 $query = "SELECT c.model_name, c.lot_num, c.s1, c.s2, c.datecreated, c.date_received, c.last_date
              FROM (SELECT model_name, lot_num, status_prod1 AS s1, NOT NULL AS s2, datecreated, date_received,  NULL AS last_date FROM tbl_product1 WHERE status_prod1 = 'sent' UNION SELECT model_name, lot_num, NOT NULL AS s1, status_prod2 AS s2, NULL AS datecreated, NULL AS date_received, last_date  FROM tbl_product2 WHERE status_prod2 = 'sent')c
    ORDER BY model_name, lot_num ASC";

但结果并不像我的期望。当我运行此查询时,它显示double lot_num和model_name。我不知道如何解释。

例如,当我运行我的代码时,此输出将显示:

model_name | lot_num | status_prod1 | status_prod2
---------------------------------------------------
magic1     | 001     | sent         | 
magic1     | 001     |              |  sent
sss        | 100     | sent         |
ddd        | 222     | sent         |
ddd        | 222     |              |  sent

假设表格应该是这样的:

model_name | lot_num | status_prod1 | status_prod2
---------------------------------------------------
magic1     | 001     | sent         | sent
sss        | 100     | sent         |
ddd        | 222     | sent         | sent

2 个答案:

答案 0 :(得分:0)

如果您只想要这7列,那么简单的INNER JOIN就可以了。内连接只返回两个表中都有model_name和lot_num的行:

(UNTESTED)

SELECT 
  a.model_name, a.lot_num, a.status_prod1, a.datecreated, a.date_received
  b.status_prod2, b.last_date
FROM
  tbl_product1 a 
INNER JOIN 
  tbl_product2 b 
ON
  a.model_name = b.model_name AND a.lot_num = b.lot_num
WHERE
  b.status_prod2 = 'sent' OR a.status_prod1 = 'sent'
ORDER BY 
  a.model_name, a.lot_num ASC;

答案 1 :(得分:0)

您可以通过聚合获得所需内容:

SELECT c.model_name, c.lot_num,
       max(c.s1) as s1, max(c.s2) as s2, max(c.datecreated) as date_created,
       max(c.date_received) as date_received, max(c.last_date)
FROM (SELECT model_name, lot_num, status_prod1 AS s1, NOT NULL AS s2, datecreated, date_received,  NULL AS last_date
      FROM tbl_product1
      WHERE status_prod1 = 'sent' UNION ALL
      SELECT model_name, lot_num, NOT NULL AS s1, status_prod2 AS s2, NULL AS datecreated, NULL AS date_received, last_date 
      FROM tbl_product2
      WHERE status_prod2 = 'sent'
     ) c
GROUP BY c.model_name, c.lot_num
ORDER BY model_name, lot_num ASC