How can I make a if else statement on SQL? - php

Hi Guys I'm having a Problem on how i could make a if else statement on SQL,
It only displays the value of rent.rent_status = 1 on a Modal, but if rent.rent_status has no value the modal wont display, how can i make it display?
Here is my code for your reference;
$sql = "SELECT * FROM stall
LEFT JOIN tenant ON tenant.stall_id = stall.stall_id
LEFT JOIN rent ON rent.tenant_id = tenant.tenant_id
WHERE rent.rent_status = 1 AND stall.stall_id = 1";

You are using LEFT JOIN and then undoing the outer join in the WHERE clause. You need to move the conditions to the appropriate ON clauses:
SELECT *
FROM stall s LEFT JOIN
tenant t
ON t.stall_id = s.stall_id LEFT JOIN
rent r
ON r.tenant_id = t.tenant_id AND r.rent_status = 1
WHERE s.stall_id = 1;
A LEFT JOIN keeps all rows in the first table along with matching rows in the second table. If there is no match, then the values are NULL for the columns in the second table. Your WHERE condition fails on NULL conditions.

Maybe try Wrapping your output with code similar to this
while (mysqli_stmt_fetch($stmt)) {
if(mysqli_stmt_num_rows($stmt) > 0){'output goes here'}
}
I'm not sure how you're using your php , this is just to give you an idea to grow on.

You don't need to use if..else just use or operator....
SELECT * FROM stall
LEFT JOIN tenant ON tenant.stall_id = stall.stall_id
LEFT JOIN rent ON rent.tenant_id = tenant.tenant_id
WHERE ((rent.rent_status = 1) OR (rent.rent_status IS NULL)) AND stall.stall_id = 1"

Related

MySQL query with multiple left joins and different WHERE clauses for each

I'm modifying a query that previously left joined two tables, but now needs to add a third, and I'm struggling with some of the conditions being applied.
This is the original query:
$sql = "SELECT COUNT(act.rowId) q4Act
FROM accounts a
LEFT JOIN leads l ON a.accountId = l.accountId
LEFT JOIN activities act ON act.leadId = l.leadId AND act.classification = 'Positive' AND activityDate >= '2016-10-31' AND activityDate < '2017-02-01'
WHERE a.accountId = '$id'
GROUP BY a.accountName ";
This worked fine, ensuring that the only results from the activities table were meeting the three AND conditions and the accountId was the one being queried.
However, I split two tables and wanted to update this query. My first attempt was this next query, where I added the new left join, removed a condition from the first one and added it to the second one. This, however, returns totally different results.
$sql = "SELECT COUNT(act.rowId) q4Act
FROM accounts a
LEFT JOIN leads l ON a.accountId = l.accountId
LEFT JOIN activities act ON act.leadId = l.leadId AND activityDate >= '2016-10-31' AND activityDate < '2017-02-01'
LEFT JOIN interestingMoments im ON im.rowId = act.imId AND im.classification = 'Positive'
WHERE a.accountId = '$id'
GROUP BY a.accountName ";
My next attempt was to move the condition on the new table below the joins like this:
$sql = "SELECT COUNT(act.rowId) q4Act
FROM accounts a
LEFT JOIN leads l ON a.accountId = l.accountId
LEFT JOIN activities act ON act.leadId = l.leadId AND activityDate >= '2016-10-31' AND activityDate < '2017-02-01'
LEFT JOIN interestingMoments im ON im.rowId = act.imId
WHERE a.accountId = '$id'
AND im.classification = 'Positive'
GROUP BY a.accountName ";
The above returns the same results when there's a positive count, though it doesn't return a 0 count like the first query did. This isn't a big deal, but I'd like to see if this is the proper way to construct this query.
Is this the best way, or should I be going about it a different way?
Placing the constraint on the JOIN versus in the WHERE clause really creates no difference. If the tables is huge, it may affect time to run the SELECT, but that difference is likely small and can still probably be mitigated by indexes.

Select Mysql Query inside echo of another query

Hello I would like to know how I can realizes query selection inside echo of already processed query.
This is my firs Mysql Query
SELECT * FROM cursos_modulos
foreach($result as $row)
{
$id = $row['id'];
echo"
Here where the echo goes I have to make the other query which is:
SELECT COUNT(users.userID)
FROM users
INNER JOIN subscriptions
ON users.userID = subscriptions.user_id
WHERE subscriptions.curso_id = $id
and at the end to put the result of this query
foreach($result as $rowc)
.$rowc[0]."};
Any help how I can achive this goal will be very welcome. Question is simple. First Select Selects the Cours with it's unique ID. which ID have to be used in the second, third and else... queries. Which queries are like the second one. So First Select Course and then Select different parameters from this course based on this ID. at the end dump results of each of the selections with different indications"
Do it all in one query:
SELECT c.*, count(s.curso_id) as count
FROM cursos_modulos AS c
LEFT JOIN subscriptions AS s ON s.curso_id = c.id
LEFT JOIN users AS u ON u.userID = s.user_id
The LEFT JOIN is needed to get 0 for the count if there are no matching rows in subscriptions.
To include a second count of approved subscriptions:
SELECT c.*, count(s.curso_id) as count, SUM(IF(s.approved = 'approved', 1, 0)) AS count_approved
FROM cursos_modulos AS c
LEFT JOIN subscriptions AS s ON s.curso_id = c.id
LEFT JOIN users AS u ON u.userID = s.user_id

Three times INNER JOIN SELECT

I've a page where I want to use 3 times INNER JOIN, Because log_items have a row called 'price'. When I do INNER join with log_mobs & log_mitem everything goes fine, He gets all information from $_GET['id'] combined with ['g'] but when I join with log_items he shows all rows from the table 'log_items'
I want to show on the page, the items the MOB have next to that I want to show the price.
But he shows all those information from 'log_items' I need to show items from 'log_mitem' but I need to get those prices from 'log_items'
if (isset($_GET['id']) && isset($_GET['g']))
{
$id = $db->real_escape_string(trim($_GET['id']));
$g = $db->real_escape_string(trim($_GET['g']));
$mobitem = $db->query("SELECT * FROM log_mobs INNER JOIN log_mitem INNER JOIN log_items ON log_mobs.name = log_mitem.mobname AND log_mobs.game = log_mitem.game WHERE log_mobs.name = '".$id."' AND log_mitem.game = '".$g."'") or die($db->error);
?>
I think your SQL request should look something like this:
select * from log_mobs
inner join log_mitem on log_mobs.name = log_mitem.mobname
inner join log_items on log_items.column = theOtherSideOfTheJointure.column

get count of posts based on count(*)

i am trying to get number of posts that i have
Here is my query
$Query="
SELECT t.*,u.*,c.*
FROM posts as t
LEFT JOIN relations as r on r.post_id = t.post_id
LEFT JOIN users as u on t.auther_id = u.auther_id
LEFT JOIN categories as c on c.cate_id = r.cate_id
GROUP BY t.post_id
";
$Query=mysql_query($Query);
$numberOfPosts=mysql_num_rows($Query);
This query is works very well
but i am trying to convert it, i want make it faster
i want use count(*) instead of t.*
because when i use t.*, it gets the full data of posts and categories
but i want to get count only, So i decided to use count(*) but i don't know how to use it with query like this
Edit
i've replaced SELECT t.*,u.*,c.* with SELECT count(t.*)
But i got mysql Error Warning: mysql_fetch_assoc(): supplied argument
Edit 2:
i am trying SELECT count(t.post_title)
I Got this results
Array ( [count(t.post_id)] => 10 )
But i have only 2 posts!
$Query="
SELECT t.*,u.*,c.*
FROM posts as t
LEFT JOIN relations as r on r.post_id = t.post_id
LEFT JOIN users as u on t.auther_id = u.auther_id
LEFT JOIN categories as c on c.cate_id = r.cate_id
GROUP BY t.post_id
";
$Query=mysql_query($Query);
$numberOfPosts=mysql_num_rows($Query);
Let's take a step back and analyze this query for a moment.
You're selecting everything from three out of four tables used in the query. The joins create some logic to limit what you select to the proper categories, authors, etc. At the end of the day you are getting a lot of data from the database, then in PHP simply asking it how many rows were returned (mysql_num_rows). Instead, what #Dagon is trying to suggest in comments, is that you have MySQL simply count the results, and return that.
Let's refactor your query:
$query = "
SELECT COUNT(t.post_id) AS qty
FROM posts as t
LEFT JOIN relations AS r ON r.post_id = t.post_id
LEFT JOIN users AS u ON t.auther_id = u.auther_id
LEFT JOIN categories AS c ON c.cate_id = r.cate_id
GROUP BY t.post_id
";
$result = mysql_query($query);
$result_row = mysql_fetch_assoc($result);
$numberOfPosts = $result_row['qty'];
(You could also use Barattlo's custom execute_scalar function to make it more readable.)
I would need to see your table structures to be of more help on how to optimize the query and get the desired results.
try doing this:
$Query="
SELECT count(t.*) as count_all
FROM posts as t
LEFT JOIN relations as r on r.post_id = t.post_id
LEFT JOIN users as u on t.auther_id = u.auther_id
LEFT JOIN categories as c on c.cate_id = r.cate_id
GROUP BY t.post_id
";
$Query=mysql_query($Query);
$numberOfPosts=mysql_num_rows($Query);
You want to do
SELECT count(t.id) AS count FROM ....
//do query with PDO or whatever you are using
$rows = mysql_fetch_assoc();
$num_rows = $rows['count'];
You should probably simply use
SELECT count(*) as postingcount FROM posts
Why?
Because you do not have a WHERE clause, so there are no restrictions. Your JOINS do not ADD more rows to the resultset, and in the end your GROUP BY merges every duplicate occurance of a post_id that might have occurred because of joining back into one row. The result should only be counted, so assuming that the real number you want to know is the number of data sets inside the table posts, you do not need any join, and doing count(*) really is a very fast operation on tables in MySQL.
Remember to check if mysql_query returns false, because then you have to check mysql_error() and see why your query has an error.

MySQL dynamically selecting fields within join with where clause?

so I'm having trouble selecting a field only if another fields value is not equal to 0.
So, here's what's going on.
I have 3 tables, they are - users, schools, campuses
And basically, I need to select a single users data from these 3 tables. I'd like to only select the campus_name field from campuses if the users.campus_id field is not 0.
So, something pseudo coded like this might give you a better idea..
The query is being passed in a $id variable, that has some user's id.
SELECT users.*, schools.*, (if(users.campus_id != 0) then campuses.campus_name)
FROM users, schools, campuses
WHERE users.id = '$id' (if(users.campus_id != 0) then AND campuses.id = users.campus_id)
SELECT *
FROM schools,
users LEFT OUTER JOIN campuses
ON users.campus_id != 0
AND users.campus_id = campuses.id
WHERE users.school_id = schools.id
So you are joining three tables together, you always expect a user to have a school, but they may not have a campus, and if this is the case, obviously nothing should be displayed.
The best you can do is acheive this with a LEFT JOIN on campuses.
An example based on your pseudo code below:
SELECT u.*, s.*, c.campus_name
FROM users u
INNER JOIN schools s ON u.school_id = s.school_id
LEFT JOIN campuses c ON u.campus_id = c.campus_id
WHERE u.user_id = $userId
If I understood you correctly, you want ALL the information displayed, but to display campus name ONLY if it exists? If so, I believe the following statement should do the trick:
SELECT `u`.* `s`.* if(`c`.`campus_name` != 0, `c`.`campus_name`, "") as `campus`
FROM `users` as `u`
INNER JOIN `schools` as `s` ON `u`.`school_id` = `s`.`school_id`
LEFT JOIN `campuses` as `c` ON `u`.`campus_id` = `c`.`campus_id`
WHERE `u`.`user_id` = $user_id;
Untested, written from the top of my head, could be errors in there

Categories