Can you optimize this SQL query for me? - sql

I'm running this query in 2 mysql_query calls. I would like to do the most performant thing and run it in one query. Can anyone optimize this for me:
if(mysql_num_rows(eq("select *
from player_data
where uid = $uid")) == 0 )
eq("update player_data
set uid = $uid,
`stat`= REPLACE(`stat`, '$temp_uid', '$uid')
where uid = $temp_uid");
Note: eq is just a wrapper function for mysql_query

You could try:
eq("update player_data
set uid = $uid,
`stat`=REPLACE(`stat`, '$temp_uid', '$uid')
where uid=$temp_uid
and not exists (select *
from player_data
where uid = $uid)");

if(mysql_num_rows(eq("select 1 from player_data where uid=$uid")) == 0 )
eq("update player_data set uid=$uid, `stat`=REPLACE(`stat`, '$temp_uid', '$uid') where uid=$temp_uid");
Avoid select * if you just want to get the count of rows in the table.

Will A's answer is very good, and if you do need to select a field specify it. Selecting everything is terrible for performance.

Related

Number of rows of query - Yii

i want to get the number of rows returned by a query in Yii. This is my query :
$programsAlreadyExist = $connection->createCommand('
SELECT *
FROM `cat_programme`
WHERE `programme_code` = 513')
->queryAll();
The "COUNT" keyword should return a row containing the requested number. :-)
SELECT COUNT(*) FROM cat_programme WHERE programme_code = 513
Change the SELECT to:
SELECT count (*) FROM cat_programme WHERE programme_code = '513'
Thanks !!
You could also do if via the count() method
For ecample
$programsAlreadyExist = MyModel::find()
->where(['programme_code' => '513'])
->count();

Select distinct value count laravel

I have an orders table where there is a status column.
I am trying to get the count of each status like this :
$pending = Order::where('status','=','pending')->count();
$active = Order::where('status','=','active')->count();
But this is not efficient as am having to make one call for each status type.
How can I reduce number of queries ?
To make an SQL request:
SELECT count(DISTINCT `status_id`) FROM `dbname`.orders WHERE `user_id` = '2';
In Laravel you can try the following:
$user->orders()->distinct()->count(["status_id"]);
You could try
$orders = Order::select(DB::raw('count(*) as order_count, status'))
->groupBy('status')
->get();
here is the way you write ->
$users= DB::table('table_name')->distinct()->get(['column_name']);
$users_count = $users->count();

django using .extra() got error `only a single result allowed for a SELECT that is part of an expression`

I'm trying to use .extra() where the query return more than 1 result, like :
'SELECT "books_books"."*" FROM "books_books" WHERE "books_books"."owner_id" = %s' % request.user.id
I got an error : only a single result allowed for a SELECT that is part of an expression
Try it on dev-server using sqlite3. Anybody knows how to fix this? Or my query is wrong?
EDIT:
I'm using django-simple-ratings, my model like this :
class Thread(models.Model):
#
#
ratings = Ratings()
I want to display each Thread's ratings and whether a user already rated it or not. For 2 items, it will hit 6 times, 1 for the actual Thread and 2 for accessing the ratings. The query:
threads = Thread.ratings.order_by_rating().filter(section = section)\
.select_related('creator')\
.prefetch_related('replies')
threads = threads.extra(select = dict(myratings = "SELECT SUM('section_threadrating'.'score') AS 'agg' FROM 'section_threadrating' WHERE 'section_threadrating'.'content_object_id' = 'section_thread'.'id' ",)
Then i can print each Thread's ratings without hitting the db more. For the 2nd query, i add :
#continue from extra
blahblah.extra(select = dict(myratings = '#####code above####',
voter_id = "SELECT 'section_threadrating'.'user_id' FROM 'section_threadrating' WHERE ('section_threadrating'.'content_object_id' = 'section_thread'.'id' AND 'section_threadrating'.'user_id' = '3') "))
Hard-coded the user_id. Then when i use it on template like this :
{% ifequal threads.voter_id user.id %}
#the rest of the code
I got an error : only a single result allowed for a SELECT that is part of an expression
Let me know if it's not clear enough.
The problem is in the query. Generally, when you are writing subqueries, they must return only 1 result. So a subquery like the one voter_id:
select ..., (select sectio_threadrating.user_id from ...) as voter_id from ....
is invalid, because it can return more than one result. If you are sure it will always return one result, you can use the max() or min() aggregation function:
blahblah.extra(select = dict(myratings = '#####code above####',
voter_id = "SELECT max('section_threadrating'.'user_id') FROM 'section_threadrating' WHERE ('section_threadrating'.'content_object_id' = 'section_thread'.'id' AND 'section_threadrating'.'user_id' = '3') "))
This will make the subquery always return 1 result.
Removing that hard-code, what user_id are you expecting to retrieve here? Maybe you just can't reduce to 1 user using only SQL.

select from db sql query

I have this query :
$query = mysql_query ("SELECT *
FROM saledb.application
WHERE app_id = (
SELECT app_id
FROM saledb.applicationdetails
WHERE is_hot = '1'
) LIMIT $Kvet,$Zet
");
And I have the following error:
Unable to save result set in
/home/lemondo/lemondosales.itnovations.ge/content/tpl/gtpl/main.php on
line 68
When I changing select item with MAX(app_id) it works but i need show all results. i know where is problem mysql cant choose in one query meny ID but i need alternativ query.
Use the IN predicate instead of = like os:
SELECT *
FROM saledb.application
WHERE app_id IN
(SELECT app_id
FROM saledb.applicationdetails
WHERE is_hot = '1');
$query = mysql_query ("SELECT * FROM saledb.application WHERE app_id IN (SELECT app_id FROM saledb.applicationdetails WHERE is_hot = '1') LIMIT $Kvet,$Zet");
That should do the trick. If you leave '=' and the subquery returns more than one row, you wil get that error. To match all the lines in saledb.application that have the app_id in the result set you need to use "IN" :)

How to execute query with subqueries on a table and get a Rowset object as a result in Zend?

I'm currently struggling on how to execute my query on a Table object in Zend and get a Rowset in return. Reason I need particularly THIS is because I'm modifying a code for existing project and I don't have much flexibility.
Query:
SELECT *
FROM `tblname` ud
WHERE ud.user_id = some_id
AND
(
(ud.reputation_level > 1)
OR
(
(SELECT COUNT( * )
FROM `tblname` t
WHERE t.user_id = ud.user_id
AND t.category_id <=> ud.category_id
AND t.city_id <=> ud.city_id
) = 1
)
)
Is there a way to describe this query using Select object?
Previous SQL solution was very simple and consisted of one WHERE clause:
$where = $this->getAdapter()->quoteInto("user_id = ?",$user_id);
return $this->fetchAll($where);
I need to produce same type of the result (so that it could be processed by existing code) but for more complicated query.
Things I've tried
$db = Zend_Db_Table::getDefaultAdapter();
return $db->query($sql)->fetchAll();
---------------- OR ----------------------
return $this->fetchAll($select);
---------------- OR ----------------------
return $this->_db->query($sql)->fetchAll();
But they either produce arrays instead of objects or fail with Cardinality violation message.
I would appreciate any help on how to handle SQL text queries in Zend.
$dbAdapter = Zend_Db_Table::getDefaultAdapter();
//change the fetch mode becouse you don't like the array
$dbAdapter->setFetchMode(Zend_Db::FETCH_OBJ);
$sql = "you're long sql here";
$result = $dbAdapter->fetchAll($sql);
Zend_Debug::dump($result);
exit;
For a list of all fetch modes go to Zend_Db_Adapter
To write you're query using Zend_Db_Select instead of manual string , look at Zend_Db_Slect