Return results from multiple table fields - php

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

Related

sql statement select from DB limit didn't work

i have a question which is my limit statement didn't work i want the content select from database and limit the show content in 40 only but it didn't work
here is my SQL statement with php code
$chatroomID=$_GET['chatroomID'];
$userID = $_SESSION['id'];
$sql="SELECT * FROM chatroom_chat WHERE chatroom_id ='$chatroomID'";
$result1 = mysqli_query($connection, $sql) or die(mysqli_error($connection));
while ($row = mysqli_fetch_array($result1)) {
$chat = $row['chat_id'];
$sql3 ="SELECT * FROM (
SELECT * FROM chat WHERE id = '$chat' ORDER BY id DESC LIMIT 0,40
) sub
ORDER BY id ASC ";
$getChatData = mysqli_query($connection,$sql3) or die(mysqli_error($connection));
/*here have statement to get username*/
while($row3 = mysqli_fetch_array($getChatData)) {
echo "<div>all content</div>";
}
}
does my code have any syntax error? i no sure why it didn't work
SELECT * FROM (
SELECT * FROM chat WHERE id = '$chat' ORDER BY id DESC LIMIT 40
) sub
ORDER BY id ASC

select down and up votes for each post php mysql

I have a forum where users can post questions and can upvote and downvote.
I want to get the upvote and downvote of each post.
What i did previously was do that in 3 sets queries.
$data = mysqli_query($con,"select * from posts");
while($row = mysqli_fetch_assoc($data)){
$pid = $row['post_id'];
$up = mysqli_fetch_assoc(mysqli_query("SELECT COUNT(*) as c FROM up WHERE post_id = $pid"))['c'];
$down = mysqli_fetch_assoc(mysqli_query("SELECT COUNT(*) as c FROM down WHERE post_id = $pid"))['c'];
}
Can anyone show me how can i do these things in one single query because if a get a lot of posts in 1st query then there will be lots of queries to do.
You can use subqueries and put everything in the first query.
This could be a good start :
$data = mysqli_query($con, "select posts.*, " .
"(SELECT COUNT(*) FROM up WHERE post_id = posts.post_id) as totalUp, " .
"(SELECT COUNT(*) FROM down WHERE post_id = posts.post_id) as totalDown " .
"from posts");
while($row = mysqli_fetch_assoc($data)){
// ...
}
you can use corelated subquery for this where upvotes
and downvotes are counted based on the post id
SELECT p.*,
( select count(*) from up where post_id = p.post_id ) as upVotesCount,
( select count(*) from down where post_id = p.post_id ) as downVotesCount,
FROM posts p

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.

Select random row in SQL where Status = 0 using php

I wonder... is this possible to select a random row in my DB where only the record that contains field->Status = 0 ? because i only need a row that contains 0 in the field name=Status. if the status contains = 1 , then the row will not belong in the randomization.
my code in the query is
$result = mysql_query( " SELECT * FROM `$haha` ORDER BY RAND() limit 1");<br>
$result = mysql_query( " SELECT * FROM `$haha` ORDER BY RAND() limit 1 Where Status=0");
But it does not work.. i appreciate your replies.. thank you very much!
Try below code:
$result = mysql_query("SELECT * FROM `".$haha."` Where Status=0 ORDER BY RAND() limit 0,1");
Your where clause should be before then the order by clause.
And want to know what is the value of $haha.
You use the wrong syntax. The good one:
$result = mysql_query( " SELECT * FROM `$haha` Where Status=0 ORDER BY RAND() limit 1");

How to use a Union properly with Order BY?

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

Categories