Select the result where multiple columns - php

I need to select the result with check the multiple columns.
SELECT * FROM atricle WHERE
a.article_free_1 = 1 AND
a.article_free_2 = 1 AND
a.article_free_3 = 1 AND
a.article_free_4 = 1 AND
a.article_free_5 = 1 AND
a.article_free_6 = 1 AND
a.article_free_7 = 1 AND
a.article_free_8 = 1 AND
a.article_free_9 = 1 AND
a.article_free_10 = 1;
Here I want to simplify the query.Its going very long and I need to add 40+ columns in my query.
How to simplify my query?

If you are using this query very frequently then its better to create a calculated/computed column in the table. This will be like this:
(CASE WHEN article_free_1 = 1
AND article_free_2 = 1 AND ....THEN 1 ELSE 0 END)
you can replace the query with :
SELECT * FROM atricle WHERE <computedColumn> = 1
it should simplify the query and give you optimized result eachtime you execute it.

I can't simply comment yet so I'll post as an answer.
Your query is as optimal as it can get. A calculated field will just add overhead, getting in the way of the query optimizer trying to evaluate. Whatever you do, DON'T loop in sql, it was a horrendous addition way back trying to make people like SQL. Stick to standard queries. What you got is good.
-Edit I jus read what Jeemusu wrote. spot on.

Related

How to get a SUM of all parameters in the single column of database

I need to get a SUM off all numerical entries in one of the tables of my DB
id | parameter
--------------
1 | 5
2 | 1
3 | 11
4 | 3
My php is:
$total = 'SELECT parameter FROM resource_table';
$res = $db->prepare($total);
$res->execute();
while($row4 = $res->fetch()) {
$count_sum1[$row4['parameter']][] = $row4;
}
$count_sum = array_sum( $count_sum1 );
print<<<END
$count_sum
END;
this is not working, as I can guess I am not doing something correctly.
Please help
Thanks for your help in advance
Let the database do the work:
SELECT SUM(parameter) FROM resource_table
In case you want to stick to php:
<?php
// code
while($row=$res->fetch())
$count_sum+=row["parameter"];
// code
?>
Yes, database engine supports simple operations, such as SUM(), AVG(), MIN() and lot of others... so actually you are able to do some basic operation on the specific engine. Read a documentation to your database engine, because you could use MySql, MSSQL, or plenty of others and every use its own type of functions.
But I suppose that you use MySQL, so the function is simply SUM():
SELECT SUM(parameter) FROM tableName;

Laravel, how to add on the fly condition to query with query builder

This is the problem:
How to add condition like limit or offset to a query before a union condition was made?
This is what i tried:
$query = DB::table('table_name');
$query->where(condition);
$query->orWhere(condition);
$query_no_union_yet = $query->select(field list);
$query->union(another_table);
$result_without_limit = $query->get();
$query_with_limit = $query_no_union_yet->limit(10);
$query_with_limit->union(another_table);
$result_with_limit = $query_with_limit->get();
The real code is very long and complicated but this is the situation.
When reach the row $query_with_limit->union(another_table); I add a union to the one I've made before, and this is not what i want. I have to be able to add limit at the first query only after it gave me results, and gain in this way 2 sets of results.
It's possible, Any ideas?
You could clone the object so you have two query builders which are two separate instances.
$query_no_union_yet = (clone) $query->select(field list);

plus 1 to column each time page viewed?

can someone please help i am trying to make a kind of view count, to reflect the number of times a post has been viewed.
I am trying to create a function in mysql which will add +1 to a column called read in my table. so if the count starts from 0 in the column and each time someone opens that post it adds a 1 and another 1 and another 1 for however many times the page has been accessed.
i am trying to do this but am failing miserably can someone please show me how to achieve this type of thing please.
function read_forum_set() {
global $connection;
global $forum_id;
$query = "SELECT *
FROM ptb_forum, ptb_profiles
UPDATE ptb_forum.read_forum +1
WHERE ptb_profiles.user_id = ptb_forum.from_user_id
AND ptb_forum.id = '$forum_id' ";
$read_forum_set = mysql_query($query, $connection);
confirm_query($read_forum_set);
return $read_forum_set;
}
You need an update with join:
update ptb_forum
join ptb_profiles on ptb_profiles.user_id = ptb_forum.from_user_id
set ptb_forum.read_forum = ptb_forum.read_forum + 1
where ptb_forum.id = $forum_id
Whatever you do, make sure you use update ... set column = column + 1 and not two separate queries (one to read the old count and one to update it) because only with a single update expression you will be sure that each hit is counted exactly once.
First of all it's probably better to separate the queries out for sanity sake.
As for an increment query, very simple
UPDATE table
SET column = column + 1
WHERE foo = bar

joomla-php mysql not updating a record with data from previous query

I'm counting the right answers field of a table and saving that calculated value on another table. For this I'm using two queryes, first one is the count query, i retrieve the value using loadResult(). After that i'm updating another table with this value and the date/time. The problem is that in some cases the calculated value is not being saved, only the date/time.
queries look something like this:
$sql = 'SELECT count(answer)
FROM #_questionsTable
WHERE
answer = 1
AND
testId = '.$examId;
$db->setQuery($sql);
$rightAnsCount = $db->loadResult();
$sql = 'UPDATE #__testsTable
SET finish = "'.date('Y-m-d H:i:s').'", rightAns='.$rightAnsCount.'
WHERE testId = '.$examId;
$db->setQuery($sql);
$db->Query();
answer = 1 means that the question was answered ok.
I think that when the 2nd query is executed the first one has not finished yet, but everywhere i read says that it waits that the first query is finished to go to the 2nd, and i don't know how to make the 2nd query wait for the 1st one to end.
Any help will be appreciated. Thanks!
a PHP MySQL query is synchronous ie. it completes before returning - Joomla!'s database class doesn't implement any sort of asynchronous or call-back functionality.
While you are missing a ';' that wouldn't account for it working some of the time.
How is the rightAns column defined - eg. what happens when your $rightAnsCount is 0
Turn on Joomla!'s debug mode and check the SQL that's generated in out the profile section, it looks something like this
eg.
Profile Information
Application afterLoad: 0.002 seconds, 1.20 MB
Application afterInitialise: 0.078 seconds, 6.59 MB
Application afterRoute: 0.079 seconds, 6.70 MB
Application afterDispatch: 0.213 seconds, 7.87 MB
Application afterRender: 0.220 seconds, 8.07 MB
Memory Usage
8511696
8 queries logged.
SELECT *
FROM jos_session
WHERE session_id = '5cs53hoh2hqi9ccq69brditmm7'
DELETE
FROM jos_session
WHERE ( TIME < '1332089642' )
etc...
you may need to add a semicolon to the end of your sql queries
...testId = '.$examID.';';
ah, something cppl mentioned is the key I think. You may need to account for null values from your first query.
Changing this line:
$rightAnsCount = $db->loadResult();
To this might make the difference:
$rightAnsCount = ($db->loadResult()) ? $db->loadResult() : 0;
Basically setting to 0 if there is no result.
I am pretty sure you can do this in one query instead:
$sql = 'UPDATE #__testsTable
SET finish = NOW()
, rightAns = (
SELECT count(answer)
FROM #_questionsTable
WHERE
answer = 1
AND
testId = '.$examId.'
)
WHERE testId = '.$examId;
$db->setQuery($sql);
$db->Query();
You can also update all values in all rows in your table this way by slightly modifying your query, so you can do all rows in one go. Let me know if this is what you are trying to achieve and I will rewrite the example.

MySQL IF Statement change value on the fly?

I'm not even sure if this is quite possible to do with MySQL, but I hope it is.
OK so i have this SQL command
SELECT * FROM table WHERE $WhereCondition ORDER BY ListStyle
As an example of the data in the ListStyle I might have
2000 3000 3700 3800
What I'm hoping to do is use some kind of if statement in the SQL that will allow me to check other fields in a result row so that I can change the value of the ListStyle before I use that in the page to order it appropriately.
So for instance I have fields a, b and c. Now if a and b are NOT empty and c = 100 and the ListStyle = 3700, I want to change the value of ListStyle to 3699 so that when I print out a result loop, rows that match the condition ( a != '', b != '', c = 100 and ListStyle = 3700) will then be shown above the rows that have the ListStyle of 3700
I can't simply edit the data in the database, even though that would be an easy solution. The data has to stay as it is.
I originally tried doing this in php. While its easy enough to change the value of the ListStyle using if statements, I don't know of an easy way to then actually order my results without sticking everything into an array and then sorting through it. I really don't want to do that as it would mean re-writing a lot of code, which is why I'm hoping this is all possible to do in MySQL.
Can anyone help with this?
try something like:
SELECT * FROM table_name WHERE $WhereCondition ORDER BY CASE
WHEN ( a = 0, b = 0, c = 100 and ListStyle = 3700) THEN 1
WHEN ( a = 10, b = 20, c = 200 and ListStyle = 3400) THEN 2
ELSE 10
END
You can use IF or CASE inside the ORDER BY statement like
...
ORDER BY
IF(condition1, then_value, else_value)
How about this?
SELECT a,b,c, IF($condition, 3700, 3699) AS order WHERE $whereCondition ORDER BY order
Expressing $condition in MySQL might be tedious, but I think it's possible.
You can use triggers

Categories