1

Possible Duplicate:
What is the difference between Join and Union?

How do we combine separate queries into single sql statement? example:

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'

Now, I am aware of nested queryes, so I could write this like this:

but I was wondering if there is a better way to write this query?

[Update2] here is a version without variables, hope its more clear this time

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'

here I only interested in tblcustomfieldvalues.value

Community
  • 1
  • 1
CuriousMind
  • 33,537
  • 28
  • 98
  • 137

4 Answers4

1

What about:

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'
imm
  • 5,837
  • 1
  • 26
  • 32
1

You can use INNER or LEFT JOIN for that depending on your need.

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'
John Woo
  • 258,903
  • 69
  • 498
  • 492
  • this query works fine except the fact, it returns multiple different records but if I run 3seperate queries, it returns me a single unique record. – CuriousMind Jun 18 '12 at 23:47
  • i have updated the answer. I removed the two columns since you only need this column: `tblcustomfieldvalues.value` Right? – John Woo Jun 18 '12 at 23:52
0

If you want to get rows from all three tables only where rows exist in all three tables, which is what I am assuming you want, the SQL looks like this:

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
Fluffeh
  • 33,228
  • 16
  • 67
  • 80
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'

TRY THIS

M_A_K
  • 378
  • 3
  • 16