Count Query Causing "excessive Processor Usage"
For the second time in the past 6 months my hosts have shut down my site because it was apparently causing a shared mySQL 5 server to max out at 100% usage. I'm not much a programmer, know even less about mySQL and obviously don't have access to the server from the back end but I'd appreciate any advice as to whether it is my query that is causing the problem:
Set rsMail = objConnC.Execute("SELECT * ,(SELECT COUNT(*) FROM comments WHERE comments.submissionID = submissions.submissionID AND comments.commentInclude = 1) as CommentCount FROM submissions WHERE PigeonHole = 'mailbag' AND Status <> 'hold' ORDER BY submissionID DESC LIMIT 20")
Apart from two instances, this query has been working fine on a page that receives between 10,000 and 30,000 visits a day.
The site is running on Windows and coded in ASP but is calling a separate mySQL server.
View Complete Forum Thread with Replies
See Related Forum Messages: Follow the Links Below to View Complete Thread
Count User Comments In Each Category (was "help On A Query")
I would really appreciate if someone could help me out on this one. this are my tables: comments Comment_ID Video_ID Comment_Text Comment_UserID .... video Video_ID Category_ID ..... category Category_ID Category_Name I'm trying to get a user's count of comments for each category, ordered by the number of comments DESC. basically, I want to show the top categories where the user has posted the highest number of comments. so far this query gets me the category name of where the user has posted: PHP $SQLTemp = "SELECT Category_Name FROM category WHERE Category_ID IN ( SELECT DISTINCT ( Category_ID ) FROM video WHERE Video_ID IN ( SELECT DISTINCT ( Video_ID ) FROM comments WHERE Comment_UserID = $id ) )"; THANKS!!
Count Of *unique* Visits By Page For Each Day (was "Need Help With Query")
Using MySQL 4.1 I have a table 'orders' with the following fields: ipaddress pagenum xtime (which is just the yearmonthday) this is the query: SELECT distinct pagenum,ipaddress,xtime,count(pagenum) AS pagenumtotal FROM `orders` group by pagenum,xtime ORDER by xtime, pagenum asc What I am trying to do is return a count of *unique* visits by page for each day. This query returns a count of *all* visits by page for each day, including repeats. So if a visitors hits a certain page on the site 10 times and adds a record 10 times, the count result will include all 10 records in the count. I want this to only count as 1.
Add COUNT(*) To Already Existing Query (was "How To Do This")
I have this query: PHP SELECT entries.*, categories.*, uploads.*, entries.blog_id FROM entriesINNER JOIN categories ON (categories.category_id = entries.category_id) LEFT JOIN uploads ON(uploads.blog_id = entries.blog_id) LEFT JOIN images ON (images.blog_id = entries.blog_id) ORDER BY entries.date_submitted DESC LIMIT 3 Now i want to add this PHP SELECT COUNT(*) FROM comments but i dont know how to add it into the already existing query. The messages table has a column blog_id column in it so i could do a join like thisd LEFT JOIN comments ON PHP (comments.blog_id = entries.blog_id) but i dont know how to get the first bit in there
How To Fix "Column Count Doesn't Match Value Count At Row 1" ?
I've been trying to install a portal to my installation of Invision Power Board, and I keep coming up with this problem. I post here for two reasons: firstly is that no one is responding over at the portal creator's thread and I need help, second is that this error looks like a mySQL error that could be solved without the need of the creator if possible. Here is the error returned: mySQL query error: INSERT INTO `ibf_portal_box` VALUES (1, 'lang.last_topics', '<box><menu>10,20,30,50</menu> <topics_show>10</topics_show> <order>last_post</order> <exforums></exforums> </box>', 0, 'middle', '*', 0, 4, 'last_topics', '1') mySQL error: Column count doesn't match value count at row 1 mySQL error code: Date: Tuesday 21st of December 2004 08:43:10 PM I am very new to mySQL and don't really understand it. What is wrong with the above that it is trying to insert, and how is it fixed?
"Warnings" Count When Using Mysqlimport
When using mysqlimport, the final statistics include a count of "Warnings", for example: Connecting to foo.whatever.com Selecting database foo Loading data from LOCAL file: foo_userInfo.imp into foo_userInfo foo.foo_userInfo: Records: 248 Deleted: 0 Skipped: 6 Warnings: 248 Disconnecting from foo.whatever.com I'd like to know what the warnings were, however there doesn't appear to be a command line option that might be used to expand the statistics or otherwise output the text of the warnings (--verbose does not do it). Is there any way to view the warnings?
Count(*) Returns "Resource Id#3"
I have table: CREATE TABLE users( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, nick varchar(32), passw varchar(32), email varchar(128), email_poskytovatel varchar(64)); and I want to read variabile id . I am using command SELECT Count(id) FROM users. But it returns "Resource id#3". Where is my problem?
About "Select Count(*)" Always Returns 0.
my mysql version is: Ver 14.7 Distrib 4.1.14, for pc-linux-gnu (i686) using EditLine wrapper OS: uname -a Linux backup_srv1 2.4.29 #4 SMP Thu Mar 24 10:31:26 CST 2005 i686 unknown unknown GNU/Linux Desc: My statement is "SELECT COUNT(1) FROM t_card_info_035 WHERE Fcommodity_id = 0x1111 AND Fseller_uin =111111 AND Fdeal_id = 12345;" my client is a daemon, when it started, it can return the correct result, (such as 4 ) but after two or three days later, it always returns 0. I had gdb into it and find that the result in the result row is 0. but when I restart my daemon program, it will be ok again. This made me crazy... it is a mysql c API bug or something else? My daemon client is programmed by c++ , and use the c API to connect mysql. I had check that there is nothing wrong with my code, and it has no memory leak or somthing else.
Searching For Numbers - "close To" Or "approximate"
I would like to know how to search a table for records where a particular field is "close to" a particular number. For instance, let's say I have a table containing students and their most recent test scores. I'd like to see students who scored 7/10. That's easy enough (select * from table where score = 7). I'd also like to run another query to identify other students whose scores are not 7 but "close to" 7. Ie students who scored 6 or 8. As an added bonus, I'd like to be able to do a related search that shows students who scored 7, then shows the other students ordered by how "close" they are to 7. Ie students who scored 6 or 8 are "closest" matches, and students who scored 1 are "furthest". I hope this makes sense! Is there any pre-existing MySQL command that will do this? Or will I have to run separate queries for each value?
REQ: MySQL 4.0 Equivilent Of "DateDiff("m", Date, Now())=1"
I have a query that works in the rest of the SQL world "SELECT invoice.*, invoice.Date FROM invoice WHERE (DateDiff("m", Date, Now())=1);" which will give me all of last month's invoices. However it doesn't work with MySQL 4.0. While "SELECT Invoice.* FROM invoice WHERE (Month(Invoice.Date) = ((Month(Now()))-1))" Is a close substituent, it will blowup in January. Anyone have an equivalent expression for MySQL 4.0?
Get Average Of A "count"
How to get average of a count(user); Following syntax run very well $records = mysql_query( "SELECT user,action,count(user) FROM log where date='$datetr2' and action='add' group by action,user") But now I also want avg(count(user)), but it didn't work $records = mysql_query( "SELECT user,action,count(user) ,avg(count(user)) FROM log where date='$datetr2' and action='add' group by action,user") count(user) only get hot many times a user log into the webside a day. Right now I want to know the average times of user logging into the web within month. I don't know to get average number. avg() function doesn't work here.
Create Single Query From Queries On Two Tables (was "Help With Query...")
I read from other thread that query inside loop is not good idea. May I ask some help how can I create a single query to the following code which I use loop. $sql = "SELECT * FROM mytable order by points desc limit 10"; $rec = mysql_query($sql) or die(mysql_error()); $datas = mysql_fetch_array($rec); do{ $sq = "Select * from secondtable where linkid = '$datas[id]'"; $rst = mysql_query($sq) or die(mysql_error()); $rows = mysql_fetch_array($rst); echo "$rows[somefield]"; }while($datas= mysql_fetch_array($rec)); This works perfectly but I want the second query to be out of the loop if there is a way and how.
Grab 'title' From The Table 'forum' Within The Same Query (was "Help With Query")
I have the following query for my vBulletin database: PHP $get_stats_newthreads = $db->query_read(" SELECT thread.forumid, thread.postuserid, thread.postusername, thread.threadid, thread.title, thread.lastpost, thread.forumid, thread.replycount, thread.lastposter, thread.dateline, thread.iconid, thread.views, IF(views<=replycount, replycount+1, views) AS views, thread.visible FROM " . TABLE_PREFIX . "thread AS thread WHERE NOT ISNULL(thread.threadid) AND $weekold<lastpost AND thread.visible!=0 AND (forumid=34 OR forumid=7 OR forumid=8 OR forumid=11 OR forumid=10) ORDER BY rand() DESC LIMIT 5"); and would like to grab 'title' from the table 'forum' where forum.forumid=thread.forumid
Speed / Processor Usage Of Mysql
I am running MySQL 4.0.16-nt with the myODBC connector (3.51) on an IIS5 machine. If I am inserting a record it goes like the blink of an eye - 759 inserts boom done extremely fast. Then I run an ASP script to update the 759 records just inserted like this. SQLstmt = "UPDATE tblServer3 " SQLstmt = SQLstmt & "SET fldLand=" & strLand SQLStmt = SQLStmt & " WHERE fldDate='" & strNextContact & "' AND fldName='" & strName & "';" Set RS = Conn.Execute(SQLstmt) That specifies to filter based on name & date (I cannot filter on ID) Table has a total of 29,761 records The total table size is 2.2mb It does indeed to do the update, but it is extremely slow, 759 records updated in about 5 minutes, 40 seconds. That is about 2.2 records a second. Processor utilization shoots up to about 50% usage per processor (2 processors) Code:
Count(*) In A Select Returns "1". It Should Behave Like Select Count(*)
i'm trying to make a query work properly but I got lost: SELECT *,count(*) FROM cancons c, musics m, discos d, r_discos_cancons rdc WHERE c.c_id_music = m.m_id AND rdc.rdc_id_disc = d.d_id AND d.d_id_music = m.m_id AND m.m_id = 24 GROUP BY c_id note: cancons (ca) = songs (en) discos (ca) = cd's (en) music (ca) = musician (en) don't worry for the WHERE part. i need it because of the foreign keys. this query returns a table with the title of the song and some more data. on the right side, I get another column called "count(c_id)" with the number "1" in it for each row. That's supposed to be due to the "group by" clause, I think. I'd like to get the table with the songs, as usual, and, with the same query, I'd like to get the total number of rows selected.
Design For Stock Items And Checkin/checkout Process (was "Query Help")
I'm currently in the process of trying to bodge together a simple(ish) stock system to be used on a company intranet but I've ground to a halt with a particular problem. Using a MySQL database I've got tables with 11 fields, including 'Quantity' (self explanatory) and BookOut. Now this BookOut field contains information on the user who has booked out an item including the users name, the date/time etc The problem I have is this. If an item has a quantity of 7 and a user books out 1, then his/her info is stored in BookOut but when another user books out another 1 of said item at a later stage then the previous BookOut info is overwritten. Is there a way in that everytime another item is booked out that a new line is created within a specific field? } if(!sizeof($error)){ $update_SQL = "Update joystick Set BookOut = '" . mysql_real_escape_string($BookOut) . "', PCserial = '" . mysql_real_escape_string($PCserial) . "', Quantity = Quantity - " . $Quantity . ", MachineNo = '" . mysql_real_escape_string($MachineNo) . "', Date = now() WHERE ID = " . $ID; if(! @mysql_query($update_SQL)){ $error[] = "Update SQL failed"; } The above is the query I am currently using. I'm not totally proficient with .php and have already had a lot of help getting this far.
Query To Populate A Calendar (was "Wanted The Experts Opinions (that Means YOU!)")
I am building my first calendar for a client to list All their events on a month to month basis. There are several tables of data that I need to query to populat the calendar from: Events, Committee Meetings, Lectures, and Group Actions. I was wondering: #1) Is it more effecient to query all the tables once and to store the results into an array that I can check as I loop through and output the days for the calendar? #2) OR, is it better to query all the tables for each day as I loop through and construct the calendar ouput? After formulating my question it seems like a no-brainer: That option #1 would be the most effecient, but I still would like to know your opinions. Especially if you have made a calendar before.
What Is Execution Time Of A Query Based On? (was "a Mysql Question")
when selecting data from the database, does the time taken to retrieve it vary from 56k connections to T3 connections? or does it all depends ont he general server speed/amount of connections on the db? im not sure if ive explained that in the best way for people to understand but im sure someone will get what i mean
List All Clients Not Assigned To Current User (was "Query Help Please")
I have two tables like this: *clients -- client_id -- client_name *manage -- user_id (multiple entries possible) -- client_id To assign clients to users there is a entry in the manage table of the user_id and client id. I want to list all the client_ids and client_names that are not assigned to the current user_id say 1.
Unique Combinations Of Model And Make (was "Query Question")
I'm trying to write a query and was wondering if someone could help me formulate it. Here is an example table I'm working with: Table: vehicles Model Make Ford Taurus Ford Taurus Ford F150 Chevy Tahoe Chevy Blazer Chevy Tahoe I want a query that returns all unique combinations of model and make. So the result set should be: Model Make Ford Taurus Ford F150 Chevy Blazer Chevy Tahoe I know how to return distinct values for one variable, but not for two like that. Any help is greatly appreciated.
Adjacent Theater Seats (was "mySQL Query Issue")
Having not been working with more than a simple SELECT * from table query, I am having a few issues when it comes to using more complex queries. I am currently using a query to select seats from a database using the following query: $query1 = mysql_query("SELECT struct.seatid, struct.row, struct.seatnum FROM seats as seat LEFT JOIN structure as struct USING (seatid) WHERE seat.showtimeid=".(int) $_GET['id']." && seat.available = Ƈ' && seat.timelimit < $minutes2 ORDER BY seat.seatid ASC"); For each record that is selected I want to check if either of the seats either side of it are also selected, if not then it is not to be shown. I have added a while loop below the above query and run another query following it (not sure if that makes sense, so I will paste it below!) while($rows = mysql_fetch_assoc($query1)){ $minusseat = $rows[seatid] - 1; $plusseat = $rows[seatid] + 1; $queryminusseat = mysql_query("SELECT * from seats LEFT JOIN structure WHERE seat.showtimeid=".(int) $_GET['id']." && seat.available = Ƈ' && seat.seatid == $minusseat && seat.timelimit < $minutes2"); $num_rows = mysql_num_rows($queryminusseat)or die(mysql_error()); echo "$num_rows"; //if($minusnum > 0){ //echo "$minusseat <b>" . $rows[seatid] ."</b> $plusseat <br/>"; //} else { //echo "<font color=red>$minusseat <b>" . $rows[seatid] ."</b> $plusseat <br/></font>"; //} } The code above is used below the initial query and the following error is being displayed: Quote: Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in C:Program Filesxampphtdocsprojectprototype1 ickets.php on line 154 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE seat.showtimeid=1 && seat.available = Ƈ' && seat.seatid == 1 && seat.time' at line 1
Invalid Use Of Group Function (was "Baffled By Query Error")
trying to figure out why I keep getting this error with the following query: SELECT c.account_id,a.name,a.company,SUM(c.agent_product_time) AS mins FROM account a LEFT JOIN calls c ON c.account_id = a.id WHERE c.calldate >= DATE_SUB(NOW(),INTERVAL 14 DAY) AND c.agent_id = 2 AND SUM(c.agent_product_time) >= '500' GROUP BY c.account_id ORDER BY mins ERROR: #1111 - Invalid use of group function
Most Products Flagged In The Past 24 Hours (was "Query Help")
I need a little help setting up the logic behind a query. Here is the situation: I have 2 tables. Product table. Flag table (flagID, productID, date_flagged). Users can flag products. *date_flagged is a INTEGER unix timestamp. I would like to be able to setup a query where I can pull up products that have been flagged the most in the past 24 hours. At first I figured I would COUNT() the flags and GROUP BY productID, but this of course will only give me the most flagged all time, and because of the grouping by productID will not allow me to filter it by date.
Delete Except Latest 2500 Entries (was "help With Query")
I have a table that holds information on activities. For each activity I store the following: ID, When, Description The ID is the key for the table The When column holds the datetime when the activity was added The table gets filled up pretty quickly. I would like to run a query that will delete ALL the entries except for the 2500 latest ones. The When column should be the one to use when deciding which are the 2500 latest activities Can someone show me the most efficient way of doing this?
Next And Prev DisplayOrder Values (was "Help With MySQL Query")
I have a table 'Album' containing columns 'PageID' and 'DisplayOrder' (both INT). On each page that is displayed I want to have 'previous' and 'next' links to other pages, which are arranged via the DisplayOrder column. At the moment I'm doing this in 2 separate queries: SELECT DisplayOrder FROM Album WHERE PageID = $currentPage $currentNo = [result of last query] SELECT PageID FROM Album WHERE DisplayOrder IN ($currentNo-1, $currentNo+1) Highly simplified but you get the idea. Would it be possible to combine this into one query?
Find All Games A User Has A Top 3 Score In (was "Need Help With A Query")
I am trying to create a query that will go through a scores table for me and find all the games that a user has a top 3 score in. Here are the table that are relevant I think... CREATE TABLE files ( fileid int(11) NOT NULL auto_increment, file text NOT NULL, icon text NOT NULL, filelocation int(1) NOT NULL default Ƈ', iconlocation int(1) NOT NULL default Ƈ', customcode text NOT NULL, title text NOT NULL, description text NOT NULL, keywords text NOT NULL, width int(11) NOT NULL default Ɔ', height int(11) NOT NULL default Ɔ', category int(11) NOT NULL default Ɔ', timesplayed int(11) NOT NULL default Ɔ', status int(1) NOT NULL default Ɔ', filetype int(2) NOT NULL default Ɔ', dateadded date NOT NULL default ��-00-00', rating int(11) NOT NULL default Ɔ', totalvotes int(11) NOT NULL default Ɔ', totalvotepoints int(11) NOT NULL default Ɔ', scores enum(Ɔ',Ƈ') NOT NULL default Ɔ', PRIMARY KEY (fileid) ) TYPE=MyISAM AUTO_INCREMENT=2285 ; CREATE TABLE scores ( scoreid int(11) NOT NULL auto_increment, fileid int(11) NOT NULL default Ɔ', score int(11) NOT NULL default Ɔ', username text NOT NULL, userid int(11) NOT NULL default Ɔ', usercomment text NOT NULL, dateadded date NOT NULL default ��-00-00', PRIMARY KEY (scoreid) ) TYPE=MyISAM AUTO_INCREMENT=16 ; CREATE TABLE users ( userid int(11) NOT NULL auto_increment, username text NOT NULL, password text NOT NULL, email text NOT NULL, status enum(Ƈ',Ɔ') NOT NULL default Ɔ', usergroup int(11) NOT NULL default Ƈ', joined date NOT NULL default ��-00-00', played int(11) NOT NULL default Ɔ', comments int(11) NOT NULL default Ɔ', avatar text NOT NULL, avatar_uploaded enum(Ƈ',Ɔ') NOT NULL default Ɔ', location text NOT NULL, website text NOT NULL, gender int(1) NOT NULL default Ɔ', favourite int(11) NOT NULL default Ɔ', receiveemails enum(Ƈ',Ɔ') NOT NULL default Ƈ', newpm enum(Ƈ',Ɔ') NOT NULL default Ɔ', confirmation text NOT NULL, PRIMARY KEY (userid) ) TYPE=MyISAM AUTO_INCREMENT=8 ; ( Basically the query would need to search through the scores table to find if the specified user $userid has the top 3 (by top 3 i mean 1st, 2nd, or 3rd highest score) scores of any game in the scores table. The end resukt would be a list that contained the fileid of the game the user has a top 3 score in, the actual score, and the position (1, 2, or 3) Im not sure if I am even explaining this right cause im kind of tired. I am a novice MYSQL user but this just has me stumped
Script To Change All Columns (was "mysql Query")
I have a table. I need to make some changes like change column name, change int() to var() etc. So I want to write a query that alter all the columns of the table then the data which were in the database before can be reinserted.
Models Where The Years Overlap (was "Query Help Needed")
I'm trying to formulate a query for the following example: Table: model_by_year model start_year end_year model_1 2001 2004 model_1 2003 2004 model_2 2000 2005 model_2 1998 1999 model_3 1998 2003 model_3 2002 2006 I want a query that will return all like models where the years overlap. In other words, I'd want to return model_1 and model_3, but not model_2.
"Lost Connection To MySQL Server During Query"
Bog standard SuSE 8.2 Linux install. I have installed mySQL (off the SuSE 8.2 distro CDs). I can connect locally, e.g: bealzebub> mysql -u root -p mysql -h localhost ....logs me in just fine. However, this: bealzebub> mysql -u root -p mysql -h bealzebub ....causes the connection to fail with: "ERROR 2013: Lost connection to MySQL server during query". Its the same if I try to log in from another machine.
"Lost Connection To MySQL Server During Query"
Hi, I wonder if anyone can help me with this. Bog standard SuSE 8.2 Linux install. I have installed mySQL (off the SuSE 8.2 distro CDs). I can connect locally, e.g: bealzebub> mysql -u root -p mysql -h localhost ....logs me in just fine. However, this: bealzebub> mysql -u root -p mysql -h bealzebub ....causes the connection to fail with: "ERROR 2013: Lost connection to MySQL server during query". Its the same if I try to log in from another machine. Anyone?
How To Get The Total Number Of Rows With A Query "limit" ?
I would like to paginate the results of a query on several pages. So I use a query with a limit X offset Y to display X results on a page, ok. But for the first page, I need to run the same query with a count(*) to know how many pages I will get (number total of rows/ X). The problem is my query is very slow (maybe 5s) because there is much worch to do, and on the first page, I need to run this query twice (not exactly, but ...) so the page is very very slow to load. My question is : is there a function to get the total number of rows even on a query with "limit" ? Or what could I do else?
How To Get The Total Number Of Rows With A Query "limit" ?
I would like to paginate the results of a query on several pages. So I use a query with a limit X offset Y to display X results on a page, ok. But for the first page, I need to run the same query with a count(*) to know how many pages I will get (number total of rows/ X). The problem is my query is very slow (maybe 5s) because there is much worch to do, and on the first page, I need to run this query twice (not exactly, but ...) so the page is very very slow to load. My question is : is there a function to get the total number of rows even on a query with "limit" ? Or what could I do else ?
How To Get The Total Number Of Rows With A Query "limit" ?
I would like to paginate the results of a query on several pages. So I use a query with a limit X offset Y to display X results on a page, ok. But for the first page, I need to run the same query with a count(*) to know how many pages I will get (number total of rows/ X). The problem is my query is very slow (maybe 5s) because there is much worch to do, and on the first page, I need to run this query twice (not exactly, but ...) so the page is very very slow to load. My question is : is there a function to get the total number of rows even on a query with "limit" ? Or what could I do else ?
Value "000" Stored As "0" In Text Field?
I've managed to import my data from a CSV using SQLyog Enterprise, however, I have a problem with the table storing the text value "000", MySQL truncates it to "0", unfortunately, I need the value to be stored as "000", does anyone know of any way that I can force the field to store all the characters, rather than treating it as a number? Surely a text field should treat any numbers stored within it as text?
Return A "true" Or "false"
i wanna do a "select", where if the script finds any matches, i dont wanna know about them. Instead, i just want it to return a a value: true (1) ou false (0). ie.: $sth = $dbh->prepare("SELECT * FROM maps WHERE name='algo' LIMIT 1"); $sth->execute(); if (match is true) { print "True Match. A match was found"; } else { print "False Match. No matches were found."; }
"Group By" Forgets "Order By"
I'm trying to build a simple RSS reader for a client and am running into some serious problems with the GROUP BY in MySQL. Basically I have two tables: one that holds all the entries and one that holds all the feeds. Then what I can do is say: [MYSQL]SELECT * FROM entries WHERE feed_id='13' ORDER BY date DESC[/MYSQL] That will select all the entries that belong to feed #13. This is fine, but what I'm doing now is building a library that will display the feed_id with the latest entry with that id. So I would think it would be something like the following: [MYSQL]SELECT * FROM entries GROUP BY feed_id ORDER BY date DESC[/MYSQL] That should get me the single latest entry from each feed_id. However it's forgetting the ORDER BY clause all together and seemingly ordering it by the auto-incrememnt value in the entries field.
Return Only 3 Photos From 3 Specified Galleries In One Query (was "Is It Possible?")
Let me start from the beginning.... I have a table that lists photo details, with a foreign key to link them to a gallery. Lets say I have 20 photos altogether and 4 galleries, (for simplicity sake, 5 photos per gallery). My question is: Is it possible to query the table to get it to return only 3 photos from 3 specified galleries in one query? (So returning 9 photos altogether, 3 from each gallery) Rather than querying the table 3 times with a limit of 3 and merging the results.
Want Only One Record Returned Per Post_id (was "Help With Query")
I can't figure out how to do this query. Help would be muchly appreciated! I want to get the DISTINCT(post.post_id) but not sure how to do this. Here is the query I have thus far but it's returning two records each with the same post_id but different cat_id's. SELECT post.post_id, auth_alias, pc.cat_id, post_heading, DATE_FORMAT(post_created, '%M %d, %Y'), post_body FROM posting post LEFT OUTER JOIN post_cats pc ON post.post_id = pc.post_id WHERE post_status = Ƈ' ORDER BY post.post_created DESC LIMIT 0,5
SUM(price*quantity) Not Very Accurate (was "Query HElp")
Query-Geek is back with some anoying problems, so bear with me!! hahaha i have tbl1 with category_id,price,quantity. tbl2 has total. now want to create a query that will do this select SUM(price*quantity) as total from tbl1 where category_id=1 well obviously you know what i mean..all similar category_id will have first, multiply price to quantity, then all of those should be summed up.. then save that to tbl2.
Incorporate An Additional WHERE Condition (was "Help With My Query Please?")
I’m trying to incorporate an additional statement in the below query, which works: $sql = "SELECT b.bookID, b.roomID, b.arrive, b.depart, b.status, b.property_id FROM room_booking_two b WHERE ((b.arrive BETWEEN '$d1' AND '$d2') OR (b.depart BETWEEN '$d1' AND '$d2')) ORDER BY b.roomID, b.arrive"; Now I want to add the line: WHERE b.property_id=".$_GET['property_id']) So I thought it would work like this: $sql = "SELECT b.bookID, b.roomID, b.arrive, b.depart, b.status, b.property_id FROM room_booking_two b WHERE b.property_id=".$_GET['property_id']) AND ((b.arrive BETWEEN '$d1' AND '$d2') OR (b.depart BETWEEN '$d1' AND '$d2')) ORDER BY b.roomID, b.arrive"; But that does not seem to work. Can anyone please advise?
Do The ORs Mess Up My Results? (was "query Problem")
SELECT score, comments, job_number, fname, lname, account_name FROM feedback_reports LEFT JOIN sales_reps ON sales_reps.sr_id = feedback_reports.sr_id LEFT JOIN shop_assignments ON shop_assignments.sr_id=sales_reps.sr_id LEFT JOIN users ON users.user_id=feedback_reports.user_id LEFT JOIN accounts ON accounts.account_id=users.account_id WHERE LOWER(job_number)='mh_midwest_tt_03032007' OR LOWER(fname) like '%mh_midwest_tt_03032007%' OR LOWER(lname) like '%mh_midwest_tt_03032007%' OR score='mh_midwest_tt_03032007' AND account_name='PI' My results are including records that don't have account_name='PI' Do the ORs mess that up?
Sellers Without Referenced Property Should Also Appear (was "SQL Query Help")
I have a query that joins 3 tables, one holding property details, one holding sellers details, and one holding an activity log of every operation performed. The query to list the sellers looks like this SELECT Agents_Prop_Code, sell_t.Sellers_ID, Seller_1_Prename, Seller_1_Surname, Address_Town, Tel_No, Mob_No, Seller_2_Prename, Seller_2_Surname, Email_Add, prop_t.Prop_ID, Address_Town, MAX(activity_t.Date) AS lastcomm FROM sell_t INNER JOIN prop_t ON sell_t.Sellers_ID = prop_t.Sellers_ID AND sell_t.Agency_Code =Ƈ' AND sell_t.Deleted = 'N' AND prop_t.Deleted = 'N' LEFT JOIN activity_t ON Buy_Sell = 'S' AND Ref_No = sell_t.Sellers_ID GROUP BY prop_t.Agents_Prop_Code ; However I have a problem in that if a seller has not had a property referenced to them they dont appear on the list. I think its down to the part that does .... INNER JOIN prop_t ON sell_t.Sellers_ID = prop_t.Sellers_ID .... But cant find a way forward.
Latest 3 Entries From My "friends" Query
I have a hypothetical query i'm struggling with: table1: users table2: user_posts table3: friends_association_table 1) i have a list of id's that are my "friends" that i get by querying the friends_association_table 2) i need to get the latest 3 entries from each of these friends for a total of 15 or fewer (if i only have 1 friend with 1 entry for instance) entries ignore the fiends aspect for a moment and consider only a query that asks "what are the latest 3 post entries for each of these specific users (my friends) up to a total of 15 entries"
How To Query ColumnA Or ColumnB="content"?
I need to do a query like the following for my ladder script. Essentially, I'm checking to see if there is already a row in the games table that was written today that involves the same people as the row they're currently trying to insert. If I get a positive result from the query on mysql_num_rows, I'll end the script with an error stating one must only post one match per opponent per day. $query2="SELECT winner, loser, date from ladder_games where date>$yesterday and winner=($winnerid or $memnum) and loser=($winnerid or $memnum)"; So, I want it to match true if winner=$winnerid and loser=$memnum OR if winner=$memnum and loser=$winnerid.
|