簡體   English   中英

如何將兩個表列與一個表聯接?

[英]How to join two table column with one?

我有一個mysql表用戶

username     name
---------   ------

u1           abc
u2           xyz
u3           mrz 

另一個正在交易

product     price      buyer seller
---------   ------    ------ -------

antivirus   20           u1    u3     
e-book      10           u2    u1

我想顯示為

product     price      buyer seller
---------   ------    ------ -------

antivirus   20           abc    mrz     
e-book      10           xyz    abc

我的問題是如何連接這兩個表?如何顯示數據,就像我作為row ['name']回顯的一樣,它將為買賣雙方顯示相同的名稱?

試試這個將起作用:

使用內部聯接

 SELECT t1.`product` AS `product`,t1.`price` AS `price`,t2.`name` AS `buyer`,t3.`name` AS `seller` FROM trading t1
JOIN user t2 ON t2.`username`=t1.`buyer`
JOIN user t3 ON t3.`username`=t1.`seller`

輸出:

在此處輸入圖片說明

我會在您最后一次答復時在這里回答,因為它無法正確縮進。

$result=mysql_query($query); // get the query

if(!$result){
    // if fails, do your things..
}

while($row=mysql_fetch_assoc($result)){
    // get data, i.e: print it ALL ROWS!
    echo $row['seller'];
    echo $row['price'];
    // and more...
}
mysql_free_result($result); // free the resource.

如果我沒有誤會你,那你就可以使用他們的價值觀。

選擇t.product AS產品,t.price AS價格,u1.name AS買方,u2.name AS賣方從交易t JOIN用戶u1 ON(t.buyer = u1.username)JOIN用戶u2 ON(t.buyer = u2 。用戶名);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM