MySQL获取在单个查询中加入多行的多个表

时间:2016-12-28 07:30:52

标签: php mysql sql database

表A#

C_ID   | C_NAME| C_DATE
-------+-------+--------
100    | ABC   | 11/12/16      
101    | EFG   | 12/12/16     
102    | HIJ   | 22/12/16               

表B

ID   | CID  | TYPE | PRICE
-----+------+----------------------
201  | 100  | 1    | 10
202  | 100  | 2    | 25
203  | 101  | 1    | 32
204  | 101  | 2    | 22
205  | 102  | 1    | 10
206  | 102  | 2    | 25

表C

ID   | UID   | CID    | TYPE | BID PRICE
-----+-------+--------+------+-----
201  | 1001  | 100    | 1    | 20
202  | 1001  | 101    | 2    | 40
203  | 1001  | 102    | 1    | 50
204  | 1001  | 102    | 2    | 100
205  | 1002  | 101    | 1    | 20
206  | 1002  | 101    | 2    | 40
207  | 1002  | 102    | 1    | 50
208  | 1002  | 102    | 2    | 100

嗨大家好,

我想从表A中获取所有行,如果请求的用户(即1001)在表C中有任何条目,那么对应的值(即bid_price)应该返回其他明智的bidprice应该是null

对于给定的UID 1001 ,这将是预期的结果

   A.C_ID | A.C_NAME| B.C_PRICE_1  | B.C_PRICE_2 | C.C_BID_PRICE_1 | C.C_BID_PRICE_2
    -------+---------+--------------+-------------+-----------------+---------------
100        |ABC      |10            |25           |20               | null
101        |EFG      |32            |22           |null             | 40
102        |HIJ      |10            |25           |50               |100

B.C_Price 1是WHere b.Type = 1而B.C_Price 2是WHere b.Type = 2

3 个答案:

答案 0 :(得分:0)

以下是你想要的吗?

SELECT A.C_ID,A.C_NAME,B.TYPE,B.PRICE,C.BID_PRICE
FROM TABLE_A A, TABLE_B B, TABLE_C C
WHERE A.C_ID = B.CID AND B.CID = C.CID
AND C.UOD = {yourUID};

答案 1 :(得分:0)

如果您正在寻找以下结果,请尝试此解决方案。

enter image description here

以下是查询,您可以使用,

SELECT 
    a.C_ID, 
    a.C_NAME, 
    SUM(CASE WHEN b.TYPE = 1 THEN b.PRICE END) C_PRICE_1, 
    SUM(CASE WHEN b.TYPE = 2 THEN b.PRICE END) C_PRICE_2,
    SUM(CASE WHEN c.TYPE = 1 THEN c.BID_PRICE END) C_BID_PRICE_1, 
    SUM(CASE WHEN c.TYPE = 2 THEN c.BID_PRICE END) C_BID_PRICE_2 
FROM tableA a
 JOIN tableB b 
  ON a.C_ID = b.CID
 LEFT JOIN tableC c 
  ON a.C_ID = c.CID 
   AND b.TYPE = c.TYPE
   AND c.UID = 1001
GROUP BY a.C_ID, a.C_NAME;

您可以尝试SQL demo

希望这会对你有所帮助。

答案 2 :(得分:0)

只需将表格b和c加入两次:

select 
  a.c_id, 
  a.c_name, 
  b1.price as c_price_1,
  b2.price as c_price_2,
  c1.bid_price as c_bid_price_1,
  c2.bid_price as c_bid_price_2
from a
left join (select * from b where type = 1) b1 on b1.cid =  a.c_id
left join (select * from b where type = 2) b2 on b2.cid =  a.c_id
left join (select * from c where type = 1) c1 on c1.cid =  a.c_id
left join (select * from c where type = 2) c2 on c2.cid =  a.c_id;

select 
  a.c_id, 
  a.c_name, 
  b1.price as c_price_1,
  b2.price as c_price_2,
  c1.bid_price as c_bid_price_1,
  c2.bid_price as c_bid_price_2
from a
left join b b1 on b1.cid =  a.c_id and b1.type = 1
left join b b2 on b2.cid =  a.c_id and b2.type = 2
left join c c1 on c1.cid =  a.c_id and c1.type = 1
left join c c2 on c2.cid =  a.c_id and c2.type = 2;