我这里有MySQL查询..
/***
* An ugly self joining sql.
* We want the parent's name so we have to join with the same table
* joining on child_row.parent_id = parent_row.id
* Don't remove the LIMIT from this... it might be bad.
*/
$sql = 'SELECT cNode.*, pNode.name as parent_name ';
$sql.= ' FROM t_nodes AS cNode LEFT JOIN t_nodes AS pNode ';
$sql.= ' ON cNode.parent_id = pNode.id ';
$sql.=' WHERE cNode.id = '.$id.' LIMIT 1';
有没有办法让这更优雅?
答案 0 :(得分:1)
与SQL无关,只是为了提高PHP源代码的可读性:
$sql = "
SELECT cNode.*, pNode.name as parent_name
FROM t_nodes AS cNode LEFT JOIN t_nodes AS pNode
ON cNode.parent_id = pNode.id
WHERE cNode.id = $id LIMIT 1
";
答案 1 :(得分:0)
我能想到的唯一合理的替代方案是获取父名称的相关子查询...
SELECT
cNode.*,
(SELECT name FROM t_nodes AS parent WHERE id = t_nodes.parent_id) AS parent_name
FROM
t_nodes
WHERE
cNode.id = $id
LIMIT 1