如何编写sql语句

时间:2014-11-25 07:14:40

标签: mysql

我坚持如何编写mySQL以在结合所有名称和批号的数据后检索两个表之间不同产品的不同状态。

SELECT c.name, c.lot_no, t1 AS Product 1, t2 AS Product 2
FROM (SELECT name, lot_no FROM table_product1 
UNION SELECT name, lot_no FROM table_product2 ) c
RIGHT JOIN                                                                                 table_product1.status t1 ON ((c.name = name) AND (c.lot_no = lot_no))
RIGHT JOIN
table_product2.status t2 ON ((c.name = name) AND (c.lot_no = lot_no))

table_product1:name,lot_no,status

table_product2:name,lot_no,status - >表c:name,lot_no,status product 1,status product 2

1 个答案:

答案 0 :(得分:0)

通过在BOTH状态表上执行右连接,您可以排除任何不在状态表中的产品。你可以试试这个:

SELECT
   c.name
   ,c.lot_no
   ,t1.status AS "Product 1"
   ,t2.status AS "Product 2"
FROM (
   SELECT name, lot_no FROM table_product1 
   UNION
   SELECT name, lot_no FROM table_product2
) c
JOIN table_product1 t1 ON ((c.name = name) AND (c.lot_no = lot_no))
JOIN table_product2 t2 ON ((c.name = name) AND (c.lot_no = lot_no))

如果您没有该产品的状态,则应该在任一列或两列中为空。如果要消除两列中的空值,可以添加以下内容:

WHERE t1.status is not null and t2.status is not null

(我假设t1和t2中有一列叫做#34;状态"如果列名不同,你需要改变它。)