简体   繁体   中英

How to Implement Join In Mysql to Fetch the Following Record

I am new to mysql I have three tables as follows

Table No 1 purchase

 +--------+-----------+--------+
 | UserID | productID |  traID |
 +--------+-----------+--------+
 | 525    |    2      |  602   |
 +--------+-----------+--------+
 | 525    |   1001    |  602   |
 +--------+-----------+--------+
 | 525    |   1002    |  602   |
 +--------+-----------+--------+
 | 525    |    1      |  602   |
 +--------+-----------+--------+

Table No 2 Deals

 +--------+-----------+
 | dealsid| deals_name|
 +--------+-----------+
 |   1    | First Deal|
 +--------+-----------+
 |   2    |Second Deal|
 +--------+-----------+

Table No 3 Productmaster

 +-----------+--------------+
 | productID | product_name |
 +-----------+--------------+
 | 1001      | HTML         |
 +-----------+--------------+
 | 1002      | JAVA         |
 +-----------+--------------+

I want the output of the above table as follows

(First Deal , Second Deal , HTML, JAVA)

The where Clause can be implemented to purchase.traID = 602 as I have posted on the above table.

Please help me with some mysql query.

Try this:

SELECT * 
FROM   purchase p, 
       deals d, 
       productmaster pm 
WHERE  p.productid = d.dealsid 
        OR p.productid = pm.productid AND p.traID = 602;

Try this,

SELECT pm.product_name , d.deals_name
FROM   purchase p, 
       deals d, 
       productmaster pm 
WHERE  p.productid = d.dealsid 
        OR p.productid = pm.productid 
       AND p.traID = 602;

you can use SELECT distinct instead of select I will suggest to use Stored procedure: Find result from either table and get union of it as output

CREATE PROCEDURE sp_get_product_name
(
arg_traid int
)
BEGIN
    Select pm.product_name 
    from productmaster pm 
    inner join  purchase p
    on pm.productID = p.productID
    where p.traID = arg_traid
    Union
    Select d.deals_name
    from deals d
    inner join purchase p
    on d.dealsID = p.productID
    where p.traID = arg_traid

END

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