my query take a long time to run ,why? - sql

I have a query that returns c.a 1800 records( not many) but It takes long time to ran (10 seconds) but I can not understand why?
this is my query that takes a long time:
SELECT tb_KonzeptFunktionen.Konzept AS KonzeptID, tb_KonzeptFunktionen.Funktion,
tb_KonzeptFunktionen.Version,
qryFunktionen_Übersicht.ID,
qryFunktionen_Übersicht.Fehlerpfad_Kommentar AS Kommentar,
qryFunktionen_Übersicht.Fehlerpfadname,
qryFunktionen_Übersicht.Fehlerpfad_CDT,
qryFunktionen_Übersicht.Fehlerpfad_Kommentar,
qryFunktionen_Übersicht.symptombasiert,
qryFunktionen_Übersicht.Beschreibung_vorhanden,
qryFunktionen_Übersicht.Max_Pfad,
qryFunktionen_Übersicht.Max_Info,
qryFunktionen_Übersicht.Max_Status,
qryFunktionen_Übersicht.Max_Strategie,
qryFunktionen_Übersicht.Max_Prüfplan,
qryFunktionen_Übersicht.Min_Pfad,
qryFunktionen_Übersicht.Min_Info,
qryFunktionen_Übersicht.Min_Status,
qryFunktionen_Übersicht.Min_Strategie,
qryFunktionen_Übersicht.Min_Prüfplan,
qryFunktionen_Übersicht.Sig_Pfad,
qryFunktionen_Übersicht.Sig_Info,
qryFunktionen_Übersicht.Sig_Status,
qryFunktionen_Übersicht.Sig_Strategie,
qryFunktionen_Übersicht.Sig_Prüfplan,
qryFunktionen_Übersicht.Plaus_Pfad,
qryFunktionen_Übersicht.Plaus_Info,
qryFunktionen_Übersicht.Plaus_Status,
qryFunktionen_Übersicht.Plaus_Strategie,
qryFunktionen_Übersicht.Plaus_Prüfplan,
qryFunktionen_Übersicht.Beschreibung_allgemein,
qryFunktionen_Übersicht.Funktionsname
FROM tb_KonzeptFunktionen RIGHT JOIN qryFunktionen_Übersicht
ON tb_KonzeptFunktionen.Funktion = qryFunktionen_Übersicht.Funktionsname
WHERE (((tb_KonzeptFunktionen.Konzept)=[Formulare]![frm_Fahrzeug]![ID]))
and this is another related query to above query:
SELECT tbFunktionen_Übersicht.*,
tbFunktionen.Funktionsname,
tbFunktionen.Funktionsbeschreibung,
tbFunktionen.diagnoserelevant,
tbFunktionen.ID AS FunktionsID
FROM tbFunktionen_Übersicht INNER JOIN tbFunktionen
ON tbFunktionen_Übersicht.Funktion = tbFunktionen.ID
ORDER BY tbFunktionen.Funktionsname, tbFunktionen_Übersicht.Fehlerpfadname;
I added an index to the fields that appear in ORDER oder JOINS but no effect
Would you please help me if possible?
Please refer to this post,hier you can find the answer

for me PDO brought improvement in my sql query's: http://www.php.net/manual/en/intro.pdo.php
//SQL-HANDLING*******************************************************//
//*********************************************************************//
//General Example-----------------
//$sqlHandling = new sqlHandling;
//$sqlHandling->connectSQL($sqlArray['host'], $sqlArray['user'],$sqlArray['pass'], $sqlArray['dbName']);
//$tableNameArray = $sqlHandling->showTablesSQL($sqlHandling->dbh);
class sqlHandling{
//PDO - Object/ callItOutside with: $sqlClass->dbh
public $dbh = null;
//connectDataBase-------------------//
//-----------------
//example: $dbh = connectSQL('localhost','admin','1admin','test');
//start transaction
//$dbh->beginTransaction();
//-----------------
//end transaction
//$dbh->commit();
//$dbh = null;
//-----------------
//1:SQL-Location
function connectSQL($host, $user, $pass, $dbname){
//endPrevTransaction
if($this->dbh != null){
$this->dbh->commit();
$this->dbh = null;
}
//establish connection
try{
$this->dbh = new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $pass);
$this->dbh->exec('SET CHARACTER SET utf8');
return $this->dbh;
}catch(PDOException $e){
print 'Error!: ' . $e->getMessage() . '<br/>';
die();
return FALSE;
}
}
//createColumnSQL-------------------//
//example: createColumnSQL($dbh, 'backupexample', array('SomeName1 VARCHAR(30)', 'SomeName2 VARCHAR(30)', 'SomeName3 VARCHAR(30)', 'SomeName4 VARCHAR(30)'));
//1:PDO connection/2:table/3:array holding columns
function createColumnSQL($dbh, $table, $columns){
//cicle through each array
foreach($columns as $tempColumn){
//set query
$query = 'ALTER TABLE `'.$table.'` ADD COLUMN '.$tempColumn;
//send the query
$stmt = $dbh->prepare($query);
//send the data
$stmt->execute();
}
}
}
This is only a working example for my PDO sqlHandling Class. I know retrieveAllValues won't help you further but you may adopt this code for your use.
MFG

Related

Phalcon: specific column on joined PHQL

The below PHQL generates a complex resultset like it should:
$phql = "SELECT User.*, ProductUser.* "
. "FROM ProductUser "
. "INNER JOIN User "
. "WHERE ProductUser.product_id = 5";
Replacing ProductUser.* with an existing column like ProductUser.id causes an error:
MESSAGE: The index does not exist in the row
FILE: phalcon/mvc/model/row.zep
LINE: 67
This is version 2.0.6. Is this a bug or am I making a mistake somewhere? According to the documentation it should be fine.
It was my mistake (expecting the row to always be an object).
I hope this helps someone because looping complex resultsets is not in the documentation.
$result = $this->modelsManager->createQuery($phql)->execute();
if ($result instanceof \Phalcon\Mvc\Model\Resultset\Complex) {
foreach ($result as $rows) {
foreach ($rows as $row) {
if (is_object($row)) {
$modelData = $row->toArray());
// this is what I needed
} else {
$id = $row;
}
}
}
}
First of all you're missing the ON clause in your query.
Anyways, it's easier and more error prone to use Phalcon's query builder for querying:
<?php
// modelManager is avaiable in the default DI
$queryBuilder = $this->modelsManager->createBuilder();
$queryBuilder->from(["product" => 'Path\To\ProductUser']);
// Inner join params are: the model class path, the condition for the 'ON' clause, and optionally an alias for the table
$queryBuilder->innerJoin('Path\To\User', "product.user_id = user.id", "user");
$queryBuilder->columns([
"product.*",
"user.*"
]);
$queryBuilder->where("product.id = 5");
// You can use this line to debug what was generated
// $generatedQuery = $queryBuilder->getPhql();
// var_dump($generatedQuery);
// Finish the query building
$query = $queryBuilder->getQuery();
// Execute it and get the results
$result = $query->execute();
// Now use var_dump to see how the result was fetched
var_dump($result);
exit;

Multiple between statements in sql builder

I am creating a fairly large query using laravel 4 sql builder. it roughly looks like, get data from table
where(yada yada)and where age between(yada, yada)or between(yada, yada) and where(yad yada).
But what I want is this.
where(yada yada)and where (age between(yada, yada)or between(yada, yada)) and where(yad yada).
some code:
$query = Subject::grabBasic();// start writing query, which results to grab.
$agelength = sizeof($fromAgeValue);
$count = 0;
$ageflag = 0;
foreach( array_combine($fromAgeValue, $toAgeValue) as $from=>$to ){
$count+=1;
if($ageflag==0){
if(($from!=null)&&($to!=null)){
$query = Subject::addfromAgeToAge($query, $from, $to);
$ageflag=1;
}
}else if(($from!=null)&&($to!=null)){
$query = Subject::orfromAgeToAge($query, $from, $to);
}
}
... keep adding to $query
Subject code:
static function addfromAgeToAge($query, $fromAge, $toAge){
return $query->whereBetween('Age', array($fromAge, $toAge));
}
static function orfromAgeToAge($query, $fromAge, $toAge){
return $query->orWhereBetween('Age', array($fromAge, $toAge));
}
So, is there a way to write the addToAge builder function to take in the arrays of fromage and toage values and create a statement, which when added to the rest of the query, will give the desired results. e-g. the sql query will have parentheses in the correct place.
I would also like to do this without raw queries, I suspect there is a way to do this I just haven't been able to find it.
Thanks,
I buckled and used raw queries :(
Here's what it looks like.
$agecounter = 0;// tells me how many from age to age pairs were filed out coorrectly.
foreach( array_combine($fromAgeValue, $toAgeValue) as $from=>$to ){
if(($from!=null)&&($to!=null)){
$agecounter+=1;
}
}
$agelength = sizeof($fromAgeValue);
$ageflag = 0;
foreach( array_combine($fromAgeValue, $toAgeValue) as $from=>$to ){
if($ageflag==0){
if(($from!=null)&&($to!=null)){
$query = Subject::addfromAgeToAge($query, $from, $to, $agecounter); // ages put in for loop when multiple are added.
$ageflag=1; // add or's
$agecounter -=1;
}
}else if(($from!=null)&&($to!=null)){
$query = Subject::orfromAgeToAge($query, $from, $to, $agecounter);
$agecounter -=1;
}
}
and in my Model:
static function addfromAgeToAge($query, $from, $to, $count){
if($count>1){
return $query->whereRaw('( Age between ? and ?', array($from, $to));
}
return $query-> whereBetween('Age', array($from, $to));
}
static function orfromAgeToAge($query, $from, $to, $count){
if($count==1){
return $query->orWhereRaw(' Age between ? and ?)', array($from, $to));
}
return $query->orWhereRaw(' Age between ? and ?', array($from, $to));//('Age', array($fromAge, $toAge));
}
Hope this helps someone else put ()'s in a query builder.

Nested while loop needed?

I've got this code working but it's only pulling out the first neighbourhood group that matches one of the values from the 1st query. The code is in a Node ID PHP handler in a view in Drupal.
The first query puts all of the postal codes from the government's jurisdiction into an array. The second query reads through all of the neighbourhood groups to find all those that match those in that array.
It looks like I need a second loop or something since the while that's there now isn't getting every neighbourhood groups that match any of the values in the array. Can anyone see what I'm missing?
Here's the code:
$government_nid = custom_get_groupid();
$codes_list = array();
$neighbourhood_list = array();
$results = db_query("SELECT field_jurisdiction_postal_codes_value FROM {content_field_jurisdiction_postal_codes} WHERE
nid = %d", $government_nid);
while($return_list = db_fetch_array($results)){
$codes_list[] = $return_list[field_jurisdiction_postal_codes_value];
}
$results1 = db_query("SELECT nid FROM {content_type_neighbourhood_group} WHERE
field_postal_code_3_value IN ('%s')", $codes_list);
while($return_list1 = db_fetch_array($results1)){
$neighbourhood_list[] = $return_list1[nid];
}
$neighbourhood_string = implode(', ', $neighbourhood_list);
return $neighbourhood_string;
Here's the answer:
foreach ($codes_list AS $value) {
$results1 = db_query("SELECT nid FROM {content_type_neighbourhood_group} WHERE
field_postal_code_3_value = '%s'", $value);
while($return_list1 = db_fetch_array($results1)){
$neighbourhood_list[] = $return_list1[nid];
}
}
$neighbourhood_string = implode(', ', $neighbourhood_list);
return $neighbourhood_string;

SELECT issue moving from PG_query to PDO

I have a select statement see below. Using PDO how would I recreate this same Select statement, as I want to grab two values from it and combine them into the $geomstring. I can figure out the combine, but not the first 3 lines.
$sql1 = "SELECT easting_value, northing_value FROM gridreference_tbl WHERE gridref_id='$_POST[gridref_id]'";
$result1 = pg_query($sql1);
$row1 = pg_fetch_array($result1);
$geomstring = $row1['easting_value']. $_POST['grid_eastings']." ".$row1['northing_value'].$_POST['grid_northings'];
*php website for prepared statements says *
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name = ?");
if ($stmt->execute(array($_GET['name']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
I have something similar working for populating a dropdown that partly uses this
$stmt = $conn->prepare("SELECT easting_value, northing_value FROM gridreference_tbl WHERE gridref_id=$gridref_id");
$stmt->setFetchMode(PDO::FETCH_OBJ);
Found it on php.net, I was googling the wrong stuff:
$stmt4 = $conn->prepare("SELECT easting_value, northing_value from gridreference_tbl WHERE gridref_id = 4");
$stmt4->execute();
print("PDO::FETCH_ASSOC: ");
print("Return next row as an array indexed by column name\n");
$result = $stmt4->fetch(PDO::FETCH_ASSOC);
print_r($result);
print("\n");

Data retrieval from database using perl with a foreach

$dbh_source2 = DBI->connect("dbi:Oracle:host=.......;port=......;sid=......",'..........','..........');
foreach $data_line (#raw_data) {
$SEL = "SELECT arg1,arg2 FROM TABLE_NAME WHERE DATA_NAME = '$data_line'";
$sth = $dbh_source2->prepare($SEL);
$sth->execute();
while (my #row = $sth->fetchrow_array() ) {
print #row;
print "\n";
}
}
END {
$dbh_source2->disconnect if defined($dbh_source2);
}
I am trying to grab several lines of data from a user. I want to take that data and use it to query a database and grab ARG1 and ARG2 WHERE USER_DATA = $data_line.
It will not display anything.
Here's a quick revision which uses SQL placeholders in order to keep Bobby Tables from destroying your database. It may also fix the problem you're currently having, but I haven't seen enough details of your problem yet to be sure.
my $dbh_source2 = DBI->connect("dbi:Oracle:host=.......;port=......;sid=......",'..........','..........');
my $SEL = "SELECT arg1,arg2 FROM TABLE_NAME WHERE DATA_NAME = ?";
my $sth = $dbh_source2->prepare($SEL);
foreach my $data_line (#raw_data) {
$sth->execute($data_line);
while (my #row = $sth->fetchrow_array() ) {
print #row;
print "\n";
}
}
END {
$dbh_source2->disconnect if defined($dbh_source2);
}
my $dbh_source2 = DBI->connect
("dbi:Oracle:host=.......;port=......;sid=......",'..........','..........');
my $SEL = "SELECT arg1,arg2 FROM TABLE_NAME WHERE DATA_NAME = ?";
my $sth = $dbh_source2->prepare($SEL);
foreach my $data_line (#raw_data) {
chomp $data_line;
$sth->execute($data_line);
while (my #row = $sth->fetchrow_array() ) {
print "$data_line\t #row\n";
}
}
END {
$dbh_source2->disconnect if defined($dbh_source2);
}
The issue I was having was the fact that the development database was not updated with the correct information so some of the items came up blank. When using the production database with the correct information it worked great!
Thank you all for your help!