搜尋

首頁  >  問答  >  主體

查詢多個表格的SQL SELECT語句

<p>如何取得所有來自customers1和customers2的產品(包括他們的客戶名稱)? </p> <pre class="brush:php;toolbar:false;">customer1 table cid name1 1 john 2 joe customer2 table cid name2 p1 sandy p2 linda product table pid cid pname 1 1 phone 2 2 pencil 3 p1 pen 4 p2 paper</pre> <p>結果應該是這樣的</p> <pre class="brush:php;toolbar:false;">pid cid pname name1 name2 1 1 phone john NULL 2 2 pencil joe NULL 3 p1 pen NULL sandy 4 p2 paper NULL linda</pre></p>
P粉680487967P粉680487967526 天前608

全部回覆(2)我來回復

  • P粉473363527

    P粉4733635272023-08-25 11:18:02

    SELECT pid, cid, pname, name1, name2 
    FROM customer1 c1, product p 
    WHERE p.cid=c1.cid 
    UNION SELECT pid, cid, pname, name1, name2 
    FROM customer2 c2, product p 
    WHERE p.cid=c2.cid;

    回覆
    0
  • P粉826429907

    P粉8264299072023-08-25 09:01:05

    SELECT p.pid, p.cid, p.pname, c1.name1, c2.name2
    FROM product p
    LEFT JOIN customer1 c1 ON p.cid = c1.cid
    LEFT JOIN customer2 c2 ON p.cid = c2.cid

    回覆
    0
  • 取消回覆