我正在开发一个PHP项目,我不断分析MySQL查询。问题是,有时候,这个查询有超过1000个字符,我必须手动分解它,以便我可以阅读它。
有没有办法在每个大写字词之前在此字符串中添加<br>
?
例如,此查询:
SELECT Cid0.*, Cid1.*, CId2.*, CId3.* FROM `users_cars_brands` CId0 LEFT JOIN `cars` CId1 ON CId0.cars_id = CId1.id LEFT JOIN `cars_texts` CId2 ON CId1.id = CId2.cars_id LEFT JOIN `cars_medias` CId3 WHERE CId0.users_cars_id = 1;
会变成:
SELECT Cid0.*, Cid1.*, CId2.*, CId3.*
FROM `users_cars_brands` CId0
LEFT JOIN `cars` CId1
ON CId0.cars_id = CId1.id
LEFT JOIN `cars_texts` CId2
ON CId1.id = CId2.cars_id
LEFT JOIN `cars_medias` CId3
WHERE CId0.users_cars_id = 1;
我试图在Regex中找到一种方法,但我不知道是否可能。
答案 0 :(得分:1)
我找到了一个名为JDorn的sql-formatter创建的非常有用的PHP类。
以下是输入和输出的示例:
输入:
SELECT count(*),`Column1`,`Testing`, `Testing Three` FROM `Table1` WHERE Column1 = 'testing' AND ( (`Column2` = `Column3` OR Column4 >= NOW()) ) GROUP BY Column1 ORDER BY Column3 DESC LIMIT 5,10
输出:
答案 1 :(得分:0)
您可以使用SQL预处理器,例如http://www.dpriver.com/pp/sqlformat.htm
这是示例查询的输出:
SELECT cid0.*,
cid1.*,
cid2.*,
cid3.*
FROM `users_cars_brands` cid0
LEFT JOIN `cars` cid1
ON cid0.cars_id = cid1.id
LEFT JOIN `cars_texts` cid2
ON cid1.id = cid2.cars_id
LEFT JOIN `cars_medias` cid3
WHERE cid0.users_cars_id = 1;
或http://sqlformat.org/,这是输出:
SELECT Cid0.*,
Cid1.*,
CId2.*,
CId3.*
FROM `users_cars_brands` CId0
LEFT JOIN `cars` CId1 ON CId0.cars_id = CId1.id
LEFT JOIN `cars_texts` CId2 ON CId1.id = CId2.cars_id
LEFT JOIN `cars_medias` CId3
WHERE CId0.users_cars_id = 1;
答案 2 :(得分:0)
您实际上也可以使用正则表达式查找位置。在这里,不会消耗任何字符,而是引擎会查找可用于插入内容的正确位置(在您的情况下是换行符)。以下正则表达式使用前瞻和一些替代方案(也可以扩展):
<?php
$sql = "SELECT Cid0.*, Cid1.*, CId2.*, CId3.* FROM `users_cars_brands` CId0 LEFT JOIN `cars` CId1 ON CId0.cars_id = CId1.id LEFT JOIN `cars_texts` CId2 ON CId1.id = CId2.cars_id LEFT JOIN `cars_medias` CId3 WHERE CId0.users_cars_id = 1;";
$regex = '~
(?=(?:FROM|LEFT|ON|WHERE))
# search for a place where one of the words follow immediately
~x';
$sql = preg_replace($regex, "\n", $sql);
echo $sql;
/* produces:
SELECT Cid0.*, Cid1.*, CId2.*, CId3.*
FROM `users_cars_brands` CId0
LEFT JOIN `cars` CId1
ON CId0.cars_id = CId1.id
LEFT JOIN `cars_texts` CId2
ON CId1.id = CId2.cars_id
LEFT JOIN `cars_medias` CId3
WHERE CId0.users_cars_id = 1;
*/
?>