I have to write the following query in zend-framework2
select count(*) from
(
select * from table1
UNION
select * from table2
)
as a
where col1 = condition1 and col2 = condition2;
I have done union of two tables using -
$select1 = new Select('table1');
$select2 = new Select("table2");
$select1->combine($select2);
I don't know how to give an alias after doing the union of two tables and how to get the count of data.
After $select1->combine($select2); -
$sql = new Sql($this->tableGateway->adapter);
$select_string = $sql->getSqlStringForSqlObject($select1);
$sql_string = 'SELECT * FROM (' . $select_string . ') AS select_union WHERE col1 = condition1 and col2 = condition2';
$statement = $this->tableGateway->adapter->createStatement($sql_string);
$resultSet = $statement->execute();
$total_records = count($resultSet);
$resultSet gives data.
$total_records gives total no. of records.
Related
I've got returns results from a query but I would like it to return multiple results, this is the current query:
$qry = "SELECT * FROM properties WHERE isLeased = 0 AND featured = 1 ORDER BY RAND() LIMIT 9";
$res = mysqli_query($mysqli, $qry) or die('-1' . mysqli_error());
What I would like is for it to return those results, as well as the results for:
$qry = "SELECT * FROM properties WHERE isLeased = 0 AND propertyType = 'For Sale' ORDER BY RAND() LIMIT 3";
$res = mysqli_query($mysqli, $qry) or die('-1' . mysqli_error());
But if I just add the second section of code below the first one it only returns the results of the first one.
How could I tell it to return results based on a couple of tables?
You can use a UNION query:
SELECT t1.*
FROM
(
SELECT *
FROM properties
WHERE isLeased = 0 AND featured = 1
ORDER BY RAND()
LIMIT 9
) t1
UNION ALL
SELECT t2.*
FROM
(
SELECT *
FROM properties
WHERE isLeased = 0 AND propertyType = 'For Sale'
ORDER BY RAND()
LIMIT 3
) t2
Hi how can i avoid queries like these?
sample query:
$sql = DB::getInstance()->prepare("SELECT tb_id1 FROM table1 WHERE duedate < ?");
$sql->execute(array($currentdate));
if($sql->rowCount()){
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
$sql2 = DB::getInstance()->prepare("UPDATE table2 SET isOverdue = 1 WHERE tb_id2 = ?");
$sql2->execute(array($row["tb_id1"]));
}
}
You can use update with join and thus by not using any loop in PHP
update table2 t2
join table1 t1 on t1.tb_id1 = t2.tb_id2
set t2.isOverdue = 1
where
t1.duedate < ?
The code I have below joins 5 tables and then is suppose to sort by date_timed_added. The query worked perfectly if i only join 4 tables. For some reason after the 4th table, its giving me issues. The issue is that it sorts and displays the 5th table first and then the rest follow. How can i fix it so that it sorts date_time_added properly by querying all the other tables?
//$sid is a variable that is drawn from DB
$sql = "select `client_visit`.`visit_id`, `client_visit`.
`why_visit`, `client_visit`.`date_time_added`, `client_visit`.
`just_date`, `client_visit`.`type` from `client_visit` where
`client_visit`.`system_id` = '$sid' and `client_visit`.
`added_by` = '$sid'
UNION
select `client_notes`.`note_id`, `client_notes`.`note_name`,
`client_notes`.`date_time_added`, `client_notes`.`just_date`
, `client_notes`.`type` from `client_notes` where `client_notes`.
`added_by` = '$sid'
UNION
select `client_conditions`.`med_id`, `client_conditions`.`med_name`,
`client_conditions`.`date_time_added`, `client_conditions`.`just_date`,
`client_conditions`.`type` from `client_conditions` where
`client_conditions`.`system_id` = '$sid' and `client_conditions`.
`added_by` = '$sid'
UNION
select `client_stats`.`stat_test_id`, `client_stats`.`stat_why`,
`client_stats`.`date_time_added`, `client_stats`.`just_date`,
`client_stats`.`type`
from `client_stats` where `client_stats`.`system_id` = '$sid'
and `client_stats`.`added_by` = '$sid'
UNION
select `client_documents`.`doc_id`, `client_documents`.`doc_name`,
`client_documents`.`date_time_added`, `client_documents`.`just_date`,
`client_documents`.`type` from `client_documents` where `client_documents`.
`system_id` = '$sid' and `client_documents`.`added_by` = '$sid'
ORDER BY `date_time_added` DESC LIMIT $startrow, 20";
$query = mysql_query($sql) or die ("Error: ".mysql_error());
$result = mysql_query($sql);
if ($result == "")
{
echo "";
}
echo "";
$rows = mysql_num_rows($result);
if($rows == 0)
{
}
elseif($rows > 0)
{
while($row = mysql_fetch_array($query))
{
//Just using these two variables i can display the same row info
//for all the other tables
$stuffid = htmlspecialchars($row['visit_id']);
$title = htmlspecialchars($row['why_visit');
}
}
}
As per the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/union.html
If you want to order the ENTIRE result set, the ORDER BY clause must be placed on the LAST query in the UNION, with each query being bracketed.
(SELECT ...)
UNION
(SELECT ...)
ORDER BY ...
sth like this should do.
SELECT Tbl1.field1
FROM ( SELECT field1 FROM table1
UNION
SELECT field1 FROM table2
) Tbl1
ORDER BY Tbl1.field1
I have a php code which sums up the value of the same column from two different tables of same database and stores it in a variable. The code is mentioned below:
$sql = 'SELECT
(SELECT SUM( time_spent )
FROM '.TICKET_RESPONSE_TABLE.'
WHERE ticket_id='.db_input($id).')
+(SELECT SUM( time_spent )
FROM '.TICKET_NOTE_TABLE.'
WHERE ticket_id='.db_input($id).')
AS total_time';
$result = db_query($sql);
$cursor = mysql_fetch_row($result);
$total_time = $cursor[0];
Now,I want is to update a column in another table of the same database, with the value stored in the variable $total_time. Kindly help me with the same.
You can do a direct update instead of having on a variable.
$sql = 'UPDATE *tablename*
SET *columname* =
(SELECT SUM( time_spent )
FROM '.TICKET_RESPONSE_TABLE.'
WHERE ticket_id='.db_input($id).')
+(SELECT SUM( time_spent )
FROM '.TICKET_NOTE_TABLE.'
WHERE ticket_id='.db_input($id).')';
$result = db_query($sql);
or afterwords like this:
$sql = 'SELECT
(SELECT SUM( time_spent )
FROM '.TICKET_RESPONSE_TABLE.'
WHERE ticket_id='.db_input($id).')
+(SELECT SUM( time_spent )
FROM '.TICKET_NOTE_TABLE.'
WHERE ticket_id='.db_input($id).')
AS total_time';
$result = db_query($sql);
$cursor = mysql_fetch_row($result);
$total_time = $cursor[0];
$sql = 'SUPDATE *tablename*
SET *columname* = ' . $total_time
$result = db_query($sql);
You can make a subselect:
UPDATE table1 t1
SET t1.val1 =
(SELECT val FROM table2 t2 WHERE t2.id = t1.t2_id )
WHERE t1.val1 = '';
Why not
$sql= "INSERT INTO other table SET field_name = $total_time ";
$result = db_query($sql);
How do I get the results and count the results in one query? (Im using PDO statements)
SELECT * FROM table; // gets results
SELECT COUNT(*) FROM table; // counts results
$result = mysql_query( "SELECT * FROM table");
$count = mysql_num_rows( $result);
Using PDO:
$statement = $dbh->prepare('SELECT * FROM table');
$statement->execute();
$count = $statement->rowCount();
This will put the record count at the end of each row.
SELECT *
, COUNT(1) OVER () AS RecordCount
FROM table;
SELECT *, (select count(*) FROM table) ct FROM table
you should execute only one query...
$sql = SELECT * FROM table;
$res = mysql_query($sql);
you can have total count by mysql_num_rows(); function.. like this ..
$count = mysql_num_rows($res);