如何在Mysql中实现Join以获取以下记录

时间:2014-12-02 10:32:41

标签: php mysql database mysqli

我是mysql的新手我有三个表如下

表1购买

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

表2交易

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

表3产品主管

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

我希望上表的输出如下

(First Deal,Second Deal,HTML,JAVA)

我在上表中发布的where.traid = 602中可以实现where子句。

请帮我解决一些mysql查询。

2 个答案:

答案 0 :(得分:0)

试试这个:

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

答案 1 :(得分:0)

试试这个,

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;

您可以使用SELECT distinct代替select 我建议使用存储过程: 从任一表中查找结果并将其作为输出结合

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