根据多端选择一端的数据

时间:2009-10-07 10:07:32

标签: mysql database

我有三个表,一对多关系,如下所示。我想做的是根据他们与“tblThree”的关系从“tblOne”中选择所有数据。

所以没有查询来获取所有tblTwoID我想从tblOne中选择tblThreeID等于“输入值”

希望这是有道理的,

由于 本

tblOne

tblOneID

数据

tblTwoID


tblTwo

tblTwoID

数据

tblThreeID


tblThree

tblThreeID

数据

2 个答案:

答案 0 :(得分:0)

您需要使用join,例如:

SELECT t1.data,t3.data FROM t1,t3 WHERE t1.id = td.id AND id = #

答案 1 :(得分:0)

SELECT tblOne.*  -- use "SELECT DISTINCT tblOne.*" to avoid duplicate results
FROM tblOne
    INNER JOIN tblTwo
        ON tblOne.tblTwoID = tblTwo.tblTwoID
    INNER JOIN tblThree
        ON tblTwo.tblThreeID = tblThree.tblThreeID
WHERE tblTwo.tblThreeID = 42  -- replace "42" with the id you want to find

如果您不需要确保tblThree中存在记录,那么您根本不需要加入记录:

SELECT tblOne.*  -- use "SELECT DISTINCT tblOne.*" to avoid duplicate results
FROM tblOne
    INNER JOIN tblTwo
        ON tblOne.tblTwoID = tblTwo.tblTwoID
WHERE tblTwo.tblThreeID = 42  -- replace "42" with the id you want to find