How to use a Union properly with Order BY? - php

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

Related

PHP SQL - Multiple select from one table

I have a SELECT query from one table that works great as follows:
$sql = "SELECT count(max720) AS anzahlpositive1 from table where (((max720 - lastsignal)/lastsignal)*100) >= 1 AND (((max720 - lastsignal)/lastsignal)*100) < 2 AND max720 != ''";
$result = $conn->query($sql);
But I had 20-30 of them with other values.
For every SELECT query a new connection established.. I think thats a lot of perfomance.
Thats the 2nd:
$sql = "SELECT count(max720) AS anzahlpositive2 from table where (((max720 - lastsignal)/lastsignal)*100) >= 2 AND (((max720 - lastsignal)/lastsignal)*100) < 3 AND max720 != ''";
$result = $conn->query($sql);
Is is possible to do this in ONE select? (better performance)
I have tried with UNION (but i think its for 2 or more tables)
Is that a solution?
$sql = "SELECT 1";
$sql .= "SELECT 2";
$sql .= "SELECT 3";
...
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo $anzahlpositive1 ;
echo $anzahlpositive2 ;
echo $anzahlpositive3 ;
....
}
select count(max720) AS ...
union all
select count(max720) AS ...
You can use as many unions as you want, read the difference between union and union all, union will discard duplicates.

group rows, count grouped rows and order by grouped rows

I want to make an analytics system for a website and I am trying to row accesed urls from a db, group by url, count grouped rows and order DESC by number of grouped rows.
$sql = "SELECT COUNT(*) FROM (SELECT DISTINCT url FROM analytic) ORDER by (SELECT DISTINCT url FROM analytic)";
$countQry = mysqli_query($link, $sql);
while($arr = mysqli_fetch_array($countQry)) {
?>
<?=$arr['url']?>
<?
}
?>
thanks
Try using a GROUP BY:
SELECT url, COUNT(url) AS theCount
FROM analytic
GROUP BY url
ORDER BY theCount DESC
Here is PHP code for you to use:
$sql = "SELECT url, COUNT(url) AS theCount FROM analytic GROUP BY url ORDER BY by theCount DESC";
$countQry = mysqli_query($link, $sql);
while ($row = mysqli_fetch_array($countQry, MYSQLI_ASSOC)) {
echo $row['url'], ", ", $row['theCount'];
}

SQL Select count of repeated dates

I'm trying to select count of repeated dates and output its numbers
$user_curr_id = $_SESSION['user_id'];
$sql = "SELECT COUNT(datum) FROM table_name WHERE user_ids = $user_curr_id";
I have no idea how to do it.
2014-07-23,2014-07-23,2014-07-23 => 3
2014-07-24,2014-07-24 =>2
2014-07-25 => 1
and get $result = 3,2,1
I assume you're looking after the GROUP BY clause:
$sql = "SELECT datum, COUNT(datum) as cnt
FROM table_name
WHERE user_ids = $user_curr_id
GROUP BY datum
ORDER BY COUNT(datum) DESC;";
if your column datum is of the data type DATE.
Note
As already mentioned you're vulnerable to sql injection. You should use a parameterized prepared statement and bind your input value to this parameter like that:
$sql = "SELECT datum, COUNT(datum) cnt
FROM table_name
WHERE user_ids = ?
GROUP BY datum
ORDER BY COUNT(datum) DESC;";
$result = array();
if ($stmt = $mysqli->prepare($sql)) {
if ($stmt->bind_param('s', $user_curr_id)) {
if($res = $stmt->execute()) {
while ($row = $res->fetch_assoc()) {
$result[] = $row['cnt']; // add the content of field cnt
}
}
}
}
echo implode(',', $result);

Union of two tables and count with where condition

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.

PHP coding question

How can I grab the count value from the query MySQL query below using PHP.
Here is My MySQL code.
$dbc = mysqli_query($mysqli,"SELECT COUNT(*) FROM((SELECT users_friends.id
FROM users_friends
INNER JOIN users ON users_friends.user_id = users.user_id
WHERE users_friends.user_id = 1
AND users_friends.friendship_status = '1')
UNION
(SELECT users_friends.id
FROM users_friends
INNER JOIN users ON users_friends.friend_id = users.user_id
WHERE users_friends.friend_id = 1
AND users_friends.friendship_status = '1')) as friends");
using SQL_CALC_FOUND_ROWS should simplify things:
$dbc = mysqli_query($mysqli,"SELECT SQL_CALC_FOUND_ROWS users_friends.id
FROM users_friends
INNER JOIN users ON users_friends.user_id = users.user_id
WHERE users_friends.user_id = 1
AND users_friends.friendship_status = '1'
");
then afterwards do
$rs = mysqli_query($mysqli, "SELECT FOUND_ROWS()"));
$rec = $rs->fetch_array();
$count = $rec[0];
This method will return the number of records that match the query, ignoring any LIMIT statement, whereas using $rs->num_rows will only give you the number of records actually returned. Depends which one you want.
if ($result = mysqli_query($link, "SELECT Name FROM City LIMIT 10")) {
printf("Select returned %d rows.\n", mysqli_num_rows($result));
/* free result set */
mysqli_free_result($result);
http://us.php.net/manual/en/mysqli.query.php
Assuming that you are correctly connected to the MySQL server and your query are executed correctly, you can use the following code:
$values = mysql_fetch_row($dbc);
$count = $values[0];
Your query should look like SELECT COUNT(*) as numThings FROM xxx
The numThings is what you will reference in PHP:
$result = mysql_query("SELECT COUNT(*) as `numThings` FROM xxx");
$row = mysql_fetch_assoc($result);
$count = $row['numThings'];

Categories