如何将SQL内连接到下表中

时间:2015-03-20 11:25:59

标签: php mysql

我有3张桌子:

--------
| test |
--------
| id   | 
--------

-----------------------
| testconnection      |
-----------------------
| testid | pharmacyid |
-----------------------

-----------------------------------
| testcontent                     |
-----------------------------------
| id | testID | title | shortened |
-----------------------------------

我需要将testcontent's titleshortenedtestconnection相关联,以便字段pharmacyid与我当前的药房循环相关联。

现在看来它是什么样的:

$sql = mysql_query("SELECT * FROM pharmacies");
while($pharmacy = mysql_fetch_array($sql)) {

  and here i'd like to access testcontent's title and shortened for this particular pharmacy

}

2 个答案:

答案 0 :(得分:0)

应该是这样的:

SELECT cont.title, cont.shortened 
FROM testcontent cont
JOIN testconnection conn
ON cont.testId = conn.testId

OR

SELECT *, cont.title, cont.shortened 
FROM pharmacies p
JOIN testconnection conn
ON conn.pharmacyid = p.Id
JOIN testcontent cont
ON cont.testId = conn.testId

答案 1 :(得分:0)

试试吧

SELECT pharmacies.*,
(select title from testcontent where testcontent.testID = testconnection.testid limit 1) as title,
(select shortened from testcontent where testcontent.testID = testconnection.testid limit 1) as shortened  
FROM pharmacies 
left join testconnection on testconnection.pharmacyid = pharmacies.id 
order by pharmacies.id

我希望,它会起作用。