结合SQL查询

时间:2012-06-18 23:00:43

标签: mysql sql query-optimization

  

可能重复:
  What is the difference between Join and Union?

我们如何将单独的查询组合成单个sql语句?例如:

SELECT packageid FROM tblhosting WHERE id='$id' AND userid='$userid'
SELECT id FROM tblcustomfields WHERE relid=tblhosting.packageid AND fieldname='foo'
SELECT value FROM tblcustomfieldsvalues WHERE fieldid=tblcustomfields.id AND relid='$id'

现在,我知道嵌套查询,所以我可以这样写:

但我想知道是否有更好的方法来编写此查询?

[UPDATE2] 这里是一个没有变量的版本,希望这次更清楚

SELECT packageid FROM tblhosting WHERE id='$id' AND userid='$userid'
SELECT id FROM tblcustomfields WHERE relid=tblhosting.packageid AND fieldname='foo'
SELECT value FROM tblcustomfieldsvalues WHERE fieldid=tblcustomfields.id AND relid='$id'

这里我只对tblcustomfieldvalues.value

感兴趣

4 个答案:

答案 0 :(得分:1)

怎么样:

SELECT h.packageid, cf.id, cfv.value
FROM tblhosting h
INNER JOIN tblcustomfields cf ON (cf.relid = h.packageid)
INNER JOIN tblcustomfieldsvalues cfv ON (cfv.fieldid = cf.id)
WHERE h.id = '$serviceid'
  AND h.userid = '$userid'
  AND cf.fieldname = 'foo'

答案 1 :(得分:1)

您可以根据需要使用INNER or LEFT JOIN

SELECT  c.value
  FROM  tblhosting a INNER JOIN tblcustomfields b
            ON b.relid = a.packageid
        INNER JOIN tblcustomfieldsvalues c
            ON c.fieldid = b.id
 WHERE  a.id = '$id'  AND   
        a.userid = '$userid' AND 
        b.fieldname = 'foo'

答案 2 :(得分:0)

如果你想从所有三个表中获取行,只有所有三个表中都存在行,这就是我想要的,SQL就像这样:

select
    a.id,
    b.value,
    c.packageid
from
    tbcustomfields a,
    tblcustomfieldsvalues b,
    tblhosting c
where
    c.userid='$userid'
    and a.relid=b.relid
    and a.relid=c.packageid
    and a.fieldname='foo'
    and b.fieldid=c.id

答案 3 :(得分:0)

SELECT
  tblcustomfieldvalues.value
FROM tblhosting
  LEFT JOIN tblcustomfields
    ON tblcustomfields.relid = tblhosting.packageid
      AND tblcustomfields.fieldname = 'foo'
  LEFT JOIN tblcustomfieldsvalues
    ON tblcustomfieldsvalues.fieldid = tblcustomfields.id
      AND relid = '$id'
WHERE tblhosting.id = '$id'
    AND tblhosting.userid = '$userid'

尝试这个