多查询以从两个表

时间:2017-05-31 11:06:45

标签: php mysql mysqli

我有2个表product_soldproduct_received。我在两个表中都有共同的字段 product_sold表

product_id | reference | sold_date 1 | For designing | 2017-02-01 2 | dshdshf | 2017-02-05

product_received表

product_id | reference | received_date 4 | stock updation | 2017-03-01 2 | stock review | 2017-03-05 1 | Stocks shipment | 2017-03-06

我希望得到像

这样的结果

Product Code | Reference | Date 19mm Alimin | Stocks shipment | 2017-03-06 19mm Alimin | For Designing | 2017-02-01 Alu Tape SC | Stock review | 2017-03-06 Alu Tape SC | dshdshf | 2017-02-05 9mm Sheet Pl | Stock updation | 2017-03-01

产品名称在我的产品表中,我必须加入这两个表。我试图用mysqli_multi_query执行查询,但没有用。

我的产品表

product_id | product_name 1 | 19mm Alimin 2 | Alu Tape SC 3 | 10.5 mm 4 | 9mm Sheet Pl

2 个答案:

答案 0 :(得分:1)

可以通过两个查询来获得预期结果。 您需要JOIN和UNION ALL来组合两个查询。

 Outlook.Accounts accounts = OutlookApp.Session.Accounts;
        foreach (var acc in accounts)
        {
            var myNameSpace = OutlookApp.GetNamespace("MAPI");

            var myAddressList = myNameSpace.GetGlobalAddressList();

            Debug.Write( myAddressList.AddressEntries.Count);
            foreach (Outlook.AddressEntry addressEntry in myAddressList.AddressEntries)
            {
               // Debug.Write(addressEntry.Name);
            }

SELECT 
    product.product_name AS 'Product Code'
 ,  product_sold.reference AS 'Reference'
 ,  product_sold.sold_date AS 'Date'
FROM 
 product
INNER JOIN 
 product_sold
ON
 product.product_id = product_sold.product_id

UNION ALL

SELECT 
    product.product_name AS 'Product Code'
 ,  product_received.reference AS 'Reference'
 ,  product_received.received_date AS 'Date'
FROM 
 product
INNER JOIN 
 product_received
ON
 product.product_id = product_received.product_id

答案 1 :(得分:0)

使用UNION:

SELECT product_id, reference, sold_date as date  FROM product_sold
UNION
SELECT product_id, reference, received_date as date FROM product_received

或使用UNION ALL来获取重复值。

作为对您的编辑的回应,如果您想使用包含的加入:

SELECT `product`.`product_name`, a.* FROM 
    (SELECT product_id, reference, sold_date as date  FROM product_sold
    UNION
    SELECT product_id, reference, received_date as date FROM product_received) AS a
INNER JOIN product ON `product`.`product_id` = a.`product_id`;