开发者

SQL fetch all in a self-join construction

My current database looks like

CREATE TABLE sites(
siteId INT(11) AUTO_INCREMENT,
siteType VARCHAR(255),
siteName VARCHAR(255),
siteDomain VARCHAR(255),
PRIMARY KEY(siteId)
);
CREATE TABLE siteSites(
parentId INT(11),
childId INT(11)
)

I'm trying to join all the tables and fetch all data. like:

<?php
$q=mysql_query("SELECT * FROM sites s1, siteSites, sites s2 WHERE s1.开发者_如何学GositeId=parentId AND s2.siteId=childId");
$row=mysql_fetch_array($q);
?>

and than i want to get both the info from 's1' and 's2' out of the $row variable. is this possible and if it is than how do i do it?

thank you


SELECT s1.siteId as ParentSiteId, s1.siteType as ParentType, s1.siteName as ParentName, s1.siteDomain as ParentDomain,
       s2.siteId as ChildSiteId,  s2.siteType as ChildType,  s2.siteName as ChildName,  s2.siteDomain as ChildDomain
    FROM sites s1
        INNER JOIN siteSites ss
            ON s1.siteId = ss.parentId
        INNER JOIN sites s2
            ON ss.childId = s2.siteId


Your question isn't very clear...

If I'm making any sense of it, you'd like to pull the entire graph in a single query. If so, no, this is not possible in MySQL. Doing so would require a recursive with statement.

If not and your current query is correct, you need to alias the column names rather than select *, i.e. something like:

select s1.siteid as parent_id,
       s1.sitename as parent_name,
       ...,
       s2.siteid as child_id,
       s2.sitename as child_name,
       ...


I don't know if I understood your question.
Try this:

SELECT s1.*, s2.*
FROM sites s1 JOIN siteSites ss
ON s1.siteId = ss.parentId
JOIN sites s2
ON ss.childId = s2.siteId


You only missing the while loop:

while($row=mysql_fetch_array($q))
{
echo $row['siteName'];
echo $row['siteDomain'];
echo $row['parentId'];
// etc ..., access to values by field name
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜