Last N Rows Of The Query
SELECT expensive query ORDER BY field ASC; It generates somewhere around 2.9m rows. I want the last 10:
SELECT expensive query ORDER BY field DESC LIMIT 10
But I want them the other way around. Sure, I can do that programatically, but for "application reasons" I want that done in the query, so what I want to do is along the grounds of
SELECT expensive query ORDER BY field LIMIT 10 OFFSET rows()-10 We're using MySQL 4.0. Is there a way to achieve the above without using a temporary table?
View Complete Forum Thread with Replies
See Related Forum Messages: Follow the Links Below to View Complete Thread
Zero Rows Or One Rows Returned, Same Data And Same Query
I have a query that produces a single row (as I expect) when I run it from the mysql client (mysql 4.0.18-Max/linux, also 5.0.19-standard/OSX-intel), or from sqlgrinder (osx, uses jdbc). When I run it inside my application (a Java app connecting via jdbc), I get zero rows from this query. I tried it under phpmyadmin, and once again I get zero rows. Why do I get inconsistent results? Here's the query:
Several Rows From One Query
I've this sql-query... $sql = "INSERT INTO database (some_kind_of_id, names) VALUES $xxx, $_POST['xxx2']"; The thing is that my post xxx2 are several values that I want inserted on several rows with the values xxx in front...
SQL Query Not Outputing All Rows.
My query doesn't seem to output all 6 rows in the database only two queries and i'm unsure why. I do know it is the query as when i do SELECT * FROM case_studies It outputs all rows. The query i am usign is: select programs.program_title, programs.id, case_studies.id, case_studies.title, case_studies.author, case_studies.timestamp from case_studies, programs WHERE programs.id = case_studies.id Any ideas?
Query Help, Comparing Rows
Suppose I have the following data: +----+----------+-----+-----+-----+-----+-----+-----+-----+ | Id | Time | Sun | Mon | Tue | Wed | Thu | Fri | Sat | +----+----------+-----+-----+-----+-----+-----+-----+-----+ | 11 | 11:20:00 | F | T | T | T | F | F | F | | 12 | 11:45:00 | F | T | T | T | F | F | F | | 14 | 12:10:00 | F | T | T | T | F | F | F | | 15 | 12:35:00 | F | T | T | T | T | T | F | | 17 | 13:00:00 | F | T | T | T | T | T | T | | 18 | 13:25:00 | F | T | T | T | T | T | T | | 19 | 13:50:00 | F | T | T | T | T | T | T | | 20 | 11:28:00 | F | T | T | T | T | T | F | | 21 | 11:53:00 | F | T | T | T | T | T | F | | 22 | 12:18:00 | F | T | T | T | T | T | F | +----+----------+-----+-----+-----+-----+-----+-----+-----+ I would like to output the data by day pattern. I need some way to determine that in the above table, Mon-Wed is the same, Thu-Fri is the same and Saturday and Sunday are unique.
How Many Rows Were Affected By Query?
How do I retrieve the number of affected rows by an UPDATE query with SQL? The C API exposes mysql_affected_rows() but I can't find documentation of the SQL equivalent... I'm trying to find if an UPDATE had an effect within a stored procedure, so I can do an INSERT if there's no row to update. Doing it the other direction to generate an error to act on would be quite wasteful... one INSERT and millions of errors per day.
Eliminate Rows In A Query (without Many OR)
This is my query : SELECT cas.id,cas.noCas,cas.nomFictif,cas.prenom,cas.naissance FROM cas WHERE LEFT(noCas, 3)<'300' AND cas.id<>53 AND cas.id<>61 AND cas.id<>173 AND cas.id<>174 AND cas.id<>178 AND cas.id<>185 AND cas.id<>598 ORDER BY noCas There must be a more efficeint way to find what i want than this : AND cas.id<>53 AND cas.id<>61 AND cas.id<>173 AND cas.id<>174 AND cas.id<>178 AND cas.id<>185 AND cas.id<>598 Something like cas.id is not (list of values)...
Query With 3.3million Rows Is Slow?
I'm not that great with MySQL...so I was hoping someone could help me out. The query I'm running is too slow...can anyone tell me what I can do to speed it up..if I can at all? I was wondering if because ZipListMatrix has 3.3 million rows that 8 seconds is all the faster it's going to be. Any help is greatly appreciated! I have already "optimized" the tables.
Updating Multiple Rows In One Query
tried to find the answer with search but didn't return any answers. OK, here is the table table test ------------------------ | test_id | test_order | ------------------------ | 1 | 1 | ------------------------ | 2 | 2 | ------------------------ | 3 | 3 | ------------------------ I'm trying to change the orders in one query, but not sure how to do that. phpMyAdmin shows me the code like this Quote: $sql = 'UPDATE `test` SET `test_order` = ƈ' WHERE `test_id` = 1;' 'UPDATE `test` SET `test_order` = Ɖ' WHERE `test_id` = 2;' 'UPDATE `test` SET `test_order` = Ƈ' WHERE `test_id` = 3;' . ' ' I'v tried that but got a syntax error. MySQL version is 4.0.26, can anyone help please?
How To Update Multiple Rows With One Query?
I am using PHP/MySQL and need to update 7 rows with one query. Can someone tell me how to do the following so it will update the row for each day of the week? (This obviously doesn't work) $sql = "UPDATE business_hours SET hours='$sunday' WHERE id='$id' AND day='sunday' AND SET hours='$monday' WHERE id='$id' AND day='monday'";
Query Pulls Out Multiple Rows Even Though Theres Only One
Ive got a query thats selecting info about a product from a table called items and joining on a table called itemimages to get its associated images. The product can have more than one image. If i run the query on an item with 2 images i get 2 results for one item.....when theres only one item.....it seems to duplicate the item for each of its images.... SQL SELECT items.*, itemimages.* FROM items INNER JOIN itemimages ON (items.itemID = itemimages.itemID) WHERE categoryID = '$category' AND active = 'yes' LIMIT $start, $limit"
Retrieve Everything AND Count Rows In One Query
set rsminmax = con.execute("SELECT * FROM `minirules_minmax` where RuleId = '" & contractId & "'") set rsminmax2 = con.execute("SELECT COUNT(*) FROM `minirules_minmax` where RuleId = '" & contractId & "'") Is there any way to do this in one SQL query?
Average Query With 2 Rows From Same Table
My table: "answer" answerID answer(int) questionID(int) userID(int) answer1 is questionID = 1 answer2 is questionID = 2 WHERE userID is the same for both answer1 and answer2 I want the average of answer1/answer2: AVG(ans1/ans2), but how?
Optimizing Search Query For Millions Of Rows
I have mysql 4.1 and Im having a difficult time optimizing this query. select domain, length(domain) as len from domains where length(domain) <= ཌ' and not (domain regexp '[[:digit:]]') and domain not like '%-%' and price > Ɔ' and price < ཌ' and end > ��-12-01' order by end ASC, len ASC The following query outputs: | id | select_type | table | type | possible_keys | key | key_len | ref | rows | extra | ------------------------------------------------------------------------------------------------------------------------------------- | 1 | SIMPLE | domains | ALL | end | NULL | NULL | NULL | 2600000 | Extra where; Using filesort | My indexes are: ID - PRIMARY, Unique domain - Unique end Is there anyway this query could be optimized anymore? With only 2.6 million rows its taking a 5 or 6 seconds. It looks like its not finding the right keys.
Updating Multiple Rows With Same Fields (in One Query?)
I have 2 tables here table categories +--------------------------------------- + | cat_id | cat_name | cat_total_articles | +----------------------------------------+ | 1 | PHP | 23 | +----------------------------------------+ | 2 | MySQL | 17 | +----------------------------------------+ table articles +---------------------------- + | article_id | article_cat_id | +-----------------------------+ | 1 | 1 | +-----------------------------+ | 2 | 2 | +-----------------------------+ Now I've changed an article's category from cat1 to cat2, and I need to update cat_total_articles of both cat1 (minus 1) and cat2 (plus 1) in category table. Is it possible to combine the following queries into one statement? PHP mysql_query("UPDATE categories SET cat_total_articles = cat_total_articles + 1 WHERE cat_id = 2"); PHP mysql_query("UPDATE categories SET cat_total_articles = cat_total_articles - 1 WHERE cat_id = 1");
Help With Updating Duplicate Rows In Mysql Query.
Quote: SELECT id, count(*) AS numlist FROM products GROUP BY category, name, brands HAVING numlist > 1 ORDER BY id ASC What it does is find the duplicates. I also have a column called "app" which has a default set to "1". So now what I want to do is that when duplicates are found, I want the first duplicate row in each group to stay as a "1" and the others in the same group to be updated to a "2". I need this done for every group. How can I do this. I have looked high and low accrossed the web, but can't seem to find any solution. I have managed to find out how to group them and count the number of listings in each group, but I can't seem to figure out how to do the rest. Also, if possible, I would like it to be done with one query.
Query To Display The Rows As Colums Is Not Working!!
I want a select query to get two columns. but i need to get these columns one below the other that is consider that i have a table student in that i have 2 columns name mark. Now i want the result as Name Raj Rina Tina Marks 80 90 70 I tried the --vertical option of mysql and G option in the query. for example when i tried select *from studentsG it displayed *********** 1. row *********** name: Raj marks : 80 ********** 2. row ************ name: Rina marks : 90 ********** 3. row ************ name: Tina marks : 70 but i want to display Name Raj Rina Tina Marks 80 90 70
Query Which Gets Rows Based On A Radius, Lon And Lat Doesn't Work?
I have found this query which gets rows based on a radius. I need this for zip codes based on lon and lat's. $sql2 = "SELECT * FROM table as z WHERE (SQRT( (69.1 * (".$userLat." - z.lat)) * (69.1 * (".$userLat." - z.lat)) + (53.0 *(".$userLong." - z.lon)) * (53.0 *(".$userLong." - z.lon))) <= ".$userRadius." )"; return $sql2; $res = mysql_query($sql2, $connDB) or die(mysql_error()); $row = mysql_fetch_assoc($res); based on a test zip code gives a result like SELECT * FROM table as z WHERE (SQRT( (69.1 * (52.399834 - z.lat)) * (69.1 * (52.399834 - z.lat)) + (53.0 *(4.840762 - z.lon)) * (53.0 *(4.840762 - z.lon))) <= 100 ) the lat and lon of the test zip code are right. As you can see z.lat and z.lon don't get any value. And these would be every lat and lon in table. In my db table lon and lat are decimal(10,6) type with a default value of 0.000000
Why Does The Slow Query Log Show More Rows Than Exist?
# Time: 070528 17:14:57 # User@Host: counter[counter] @ localhost [] # Query_time: 3 Lock_time: 0 Rows_sent: 7 Rows_examined: 120647 SELECT SQL_CACHE `webpageUrl`, `webpageName`, COUNT(*) AS `count`, (COUNT(*) / (SELECT COUNT(*) FROM _1_log)) AS `pct` FROM _1_log GROUP BY `webpageUrl` ORDER BY `count` DESC LIMIT 7; mysql> select count(*) from _1_log; +----------+ | count(*) | +----------+ | 111824 | +----------+ 1 row in set (0.00 sec)
Trying To Count The Number Of Rows In A Result Set After Query
The user fills out this form to sign up to the website, the form checks the database to see if the username has already been taken with the code: $conn = mysql_connect("localhost:3306", "root", "********") or die ("Error With Connection"); echo("connected<br><br>"); $db_sel = mysql_select_db("game",$conn) or die ("Error With Database"); $check = "select * from users where 'username' = '$username'"; $db_sel = mysql_query($check,$conn) or die (mysql_error());
Creating Non-existent Rows In Query With Join
I want to make report using PivotTable/CrossTab and I used an application to create it. The problem is, I want to so show NULL value to the temp table that will be the source of my report. I'm using this query:
What Query To Check If Any Rows Exist Satisfying WHERE Clause?
I'm looking for a query that will check if any rows exists in a table according to a WHERE condition. I know I can use COUNT(*) but then mysql will do unnecessary task of counting all the rows whereas I just need true or false. So far I did this: SELECT COUNT(*) AS exists FROM mytable WHERE ... Sometimes I just select the first row and check later in php how many rows have been returned: SELECT some_col FROM mytable WHERE ... LIMIT 1 But I cannot do this check (or can I?) in sql alone and I have problems when I want to use this in a subquery, for example: SELECT id, name, (SELECT COUNT(*) FROM mytable WHERE ...) AS exists FROM othertable WHERE surname='xxx' Can I do the same without using COUNT(*)? I would like a query that returns 0 or NULL if no rows were found, or 1 (or some other value) if 1 or more rows were found.
Count One Table's Rows From Multi Table Query
here are my tables (condensed) FEEDS feed_id site_id SITE site_id site_name ARTICLES article_id feed_id link I want to create a query that returns the total number of articles for every site_id (which is unique in the SITE table). I have this: PHP $gsite = mysql_query("SELECT site.site_id, feeds.feed_id, COUNT(articles.article_id) AS acont FROM site,feeds,articles WHERE feeds.site_id = site.site_id AND articles.feed_id = feeds.feed_id group by site.site_id", $connection) or die(mysql_error()); The query does not use JOIN, ON and all that good stuff. I just need the following variables to run through a loop: site_id the number of articles rows per site_id
What's Wrong With My Query To Filter Double Entries And Skip Empty Rows?
I am trying to get filter a database table. - skip empty rows (i.e. ecardNameSender is empty) - filter double entries $sql = "SELECT COUNT(*) as total FROM tblEcards WHERE ecardNameSender != '' GROUP BY ecardEmailFriend"; $result = @mysql_query($sql, $connDB); $row = mysql_fetch_assoc($result); $totalPics = $row['total']; echo $totalPics; What's wrong with my query?
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 ?
How To Insert Multiple Rows With 1 Insert Query
I am having a form on the front end which has for example 3 rows each with 3 columns. The user enters data in all the 3 rows. When he hits the add button these should get in the database. What insert query would I write to add all of them together to the database? Do I need to use some procedure?
Help With 3 Table Query & Counting Rows In Third Table
I have three tables, a members, a vendors and a products. I'm using a query to grab all of the rows from the first two tables, matching on a primary key. This is easy and works fine. However, I'm trying to pull the number of products from the third table and it's giving me trouble. Basically, I can count the products for each vendor if products exist, but if there are no products, instead of returning 0, no rows are returning. current query looks like this: SELECT t1.*, t2.*, count(*) AS count FROM vendors as t1, members AS t2, products AS t3 WHERE t2.mem_id = t1.mem_id AND t3.vendors_id = t1.vendors_id GROUP BY t1.vendors_id; So, all of the vendors that have zero products are being left out of the results. Does anyone know if it's possible to achieve this without using a temp table?
Searching For Rows That Depend On Other Rows In Some Fashion...
Maybe this is a very stupid question. I'll try anayway. I'm using MySQL 3.23.52 on RedHat 8.0. I have a very big table (several millions of rows). Each entry actually constitute a word in a big text. Among other fields we have an ID for each word which represents the postition in the text. Now I want to search for short phrases. For example "welcome to sweden". This means i want to find all occurences of the word "welcome" with ID x, where we have the word "to" with ID x+1 and the word "sweden" with ID x+2. I've tried doing this recursively with temporary tables - but a find myself hitting a wall as i'm not allowed to refer to 2 different temporary tables in the same query... Resorting to another type of data strucutre, full text index etc.. is unfortunately not an option. We only need this as an add on feature if we can do it. We believe that indexes, data structures etc.. are near optimal as is. Please use my email for further conversion since I'm not a frequent usenet reader.
Insert New Rows With Qty Values From Existing Rows
I am trying to make all my products unique in my db. Lets say I have a row with an id, it also has all relevant details about the product and it has a quantity value of 4. What I would like to do is take the entire row and duplicate it by the number of the quantity field. This would result in the same product 4 times instead of one product with qty of 4. Reason, I am going to serialise all the products so that they each have unique barcode from the id field. I will encounter the reverse issue when running an insert statement for inputting new data, i.e. insert a new row for each item depending on its qty value??
Searching For Rows That Depend On Other Rows In Some Fashion...
Maybe this is a very stupid question. I'll try anayway. I'm using MySQL 3.23.52 on RedHat 8.0. I have a very big table (several millions of rows). Each entry actually constitute a word in a big text. Among other fields we have an ID for each word which represents the postition in the text. Now I want to search for short phrases. For example "welcome to sweden". This means i want to find all occurences of the word "welcome" with ID x, where we have the word "to" with ID x+1 and the word "sweden" with ID x+2. I've tried doing this recursively with temporary tables - but a find myself hitting a wall as i'm not allowed to refer to 2 different temporary tables in the same query... Resorting to another type of data strucutre, full text index etc.. is unfortunately not an option. We only need this as an add on feature if we can do it. We believe that indexes, data structures etc.. are near optimal as is.
Rows In T1 Not In Both T2 And T3 (was "Query Help...")
Scenario: 3 Tables Table1: -t1id -t1machine where: t1machine contains: mach01 mach02 mach03 mach04 mach05 mach06 mach07 mach08 mach09 mach10 Table2: -t2id -t2machines where: t2machines contains: mach01,mach03 mach02,mach05 Table3: -t3id -t3machines where: t3machines contains: mach06,mach07 mach08,mach10 Problem: Need to get machine in Table1 where it doesn't exist yet in both table2 and table3... Tried using NOT IN as part of a WHERE clause but doesn't bring result as I intended, in the example I should be getting mach04 and mach09.
Two Table Query: Grab Rows From One Table Even If No Related Row In Other Table
PHP $gettray = mysql_query("SELECT trailers.title, trailers.link, trailers.movie, movie.title AS mtitle FROM trailers,movie WHERE trailers.movie=movie.word ORDER BY trailerid DESC LIMIT 6",$connm); It works great, but there is one problem. It will not grab any rows from the 'trailers' table if a corresponding movie row does not exist in the 'movies' table. I want it to pull ALL rows from the 'trailers' table, even if the corresponding row in the 'movies' table does not exist yet. If the row does not exist in 'movies', the program than uses the entire trailer title like so PHP if($ttray['mtitle']) { $newttitle = explode("-",$ttray['title']); $newttitle = array_reverse($newttitle); $ttitle = $newttitle[0]; $ttitle = $ttray['mtitle'] ."- ". $ttitle; } else { $ttitle = $ttray['title']; } Thanks Ryan
Getting Rows That Are Related To Other Rows In The Same Table
I use a table to save a map using the following structure: id, x, y, owner Every occupied map filed has an owner id != 0. The owner id is = 0 for vacant fields. now the problem: New registered users need a vacant field on the map. Moreover the mapfields around this field need to be vacant as well! (sqrt((t1.x-t2.x)*(t1.x-t2.x)+(t1.y-t2.y)*(t1.y-t2.y)) <= 5.25) What I need is a query that gets those fields that have vacant fields around them. So far, all my tries to solve this problem with Joins/Suvqueries failed.
How Can I Make A Query Like Microsoft Access, And A Query From A Query
I am new to MYSQL and am trying to understand how to make queries... I am moving from Microsoft Access where it is GUI driven and easy! I can make a simple single query using MYSQL Query Browser, say: qry1: SELECT ID, Area FROM data GROUP BY Area How can I store this as a query inside MYSQL, rather than having to code it each time? In Microsoft Access I could enter a variable ($VARIABLE) and then pass by code to the query: qry2: SELECT ID, $VARIABLE FROM data GROUP BY $VARIABLE How can I store this as a query and then pass the variable from code? In Microsoft Access I could base a query on the results of another query, so following example above: qry3: SELECT qry1.Area, data.ID FROM qry1 INNER JOIN data ON qry1.Area = data.Area; How can I store this as a query in MYSQL.
Match Rows In Table B With Rows In Table A
How do I structure a query to match rows in table B with rows in table A where column in B contains strings that contain data from column in A.. Example: B.part = "abcdefg" matches A.part ="cde" I cannot put literal in query.. it must be from column data.. It's easy to match rows where columns are equal, but I can't figure out how to get a match with "substring" as shown.
Converting From Many Columns/few Rows To Few Columns/many Rows
So I have a table that looks like: Code: char_id1234(...up to 30) 582NULL416 25739NULL12 391NULLNULLNULL Each char_id is the primary key in another table, each numerical column value is the primary key (skill_id) in a third table, and each data value is the primay key (rank_id) in a fourth table. I am attempting to join all four tables into a single query, but it seems impossible without converting the table to something like this: Code: char_idskil_idrank_id 5812 5834 58416 2517 25239 25412
Don't Select Rows That Match Both Columns But DO Select Rows That Don't Match Both
I suppose it is because it is 2:30 AM but I'm having a bit of trouble figuring out the SQL I need to write. I am usually pretty good at this. Here's what I'm having trouble with. My app includes a Poll system built from scratch. Each question will run for one month. the month that the poll will run is kept in 2 columns in my table... runMonth and runYear. What i'm having trouble doing is selecting the rows that don't match both the current runMonth and current runYear. My Table... id.............Question...........runMonth...........runYear 1..............QA...................1......................2007 2..............QB...................2......................2007 3..............QC...................3......................2007 4..............QD...................4......................2007 (current month and year) 5..............QE...................5......................2007 6..............QF...................6......................2007 I can simply get the question for the current month... SELECT * FROM table WHERE runMonth = 4 AND runYear = 2007; but if I try to get all others using SELECT * FROM table WHERE runMonth != 4 AND runYear != 2007 I get an empty result set. As I should because there is nothing there that the runYear != 2007 doesn't knock out. The result set I am looking for is id.............Question...........runMonth...........runYear 1..............QA...................1......................2007 2..............QB...................2......................2007 3..............QC...................3......................2007 *********************(remove runMonth4 and runYear 2007) 5..............QE...................5......................2007 6..............QF...................6......................2007 What am I missing?
How To Create Efficient MySQL Query From A Pseudo Query
I'm trying to build a webapplication where users can search for a person having a particular preference for color and material. To store this information I use the following structure (a MySQL dump can be found at the end of this post): *table person with fields: -persid: autoincrement id -name: name of the person *table material with fields: -materialid: autoincrement id -material: name of the material eg "wood" *table color with fields: -colorid: autoincrement id -color: name of the color eg "green" *table persmaterial with fields: -persmatid: autoincrement id -persid: link to table person -materialid: link to table material *table perscolor with fields: -perscolorid: autoincrement id -persid: link to table person -colorid: link to table color In the webapplication the search can be entered by the users as a kind of pseudo query: (color=red OR color=blue) AND color=green AND material=iron My question is: how can I automatically transform this pseudo query into an efficient MySQL query? I have tried out some different options: Option 1: (SELECT p.persid FROM person p, perscolor pc, persmaterial pm WHERE p.persid=pc.persid AND (pc.colorid=1 OR pc.colorid=2) AND p.persid=pm.persid AND pm.materialid=2 GROUP BY p.persid HAVING (count(DISTINCT pc.colorid)=2 AND count(DISTINCT pm.materialid)=1)) UNION (SELECT p.persid FROM person p, perscolor pc, persmaterial pm WHERE p.persid=pc.persid AND (pc.colorid=2 OR pc.colorid=3) AND p.persid=pm.persid AND pm.materialid=2 GROUP BY p.persid HAVING (count(DISTINCT pc.colorid)=2 AND count(DISTINCT pm.materialid)=1)) Remarks: *I do not see how to turn a general pseudo query into a query like the one in option 1, except for turning the pseudo query into a sum of products form where the sulms would correspond to the UNIONs. IS there a clever way to obtain such a sum of products form from an arbitrary pseudo query? Option 2: SELECT persid FROM person p WHERE (EXISTS(SELECT * FROM perscolor pc WHERE pc.colorid=1 AND p.persid=pc.persid) OR EXISTS(SELECT * FROM perscolor pc WHERE pc.colorid=3 AND p.persid=pc.persid)) AND EXISTS(SELECT * FROM perscolor pc WHERE pc.colorid=2 AND p.persid=pc.persid) AND EXISTS(SELECT * FROM persmaterial pm WHERE pm.materialid=2 AND p.persid=pm.persid) Remarks: *very easy to get from pseudo query to MySQL query but what about performance? Option 3: SELECT p.persid FROM person p, perscolor pc, persmaterial pm WHERE p.persid=pc.persid AND (pc.colorid=1 OR pc.colorid=2 OR pc.colorid=3) AND p.persid=pm.persid AND pm.materialid=2 GROUP BY p.persid HAVING sum(case when pc.colorid in (Ƈ',Ɖ') then 1 else 0 end) >= 1 AND sum(case when pc.colorid=ƈ' then 1 else 0 end)>=1 AND sum(case when pm.materialid=ƈ' then 1 else 0 end)>=1 Remarks: *this option requires the pseudo query to be turned into a product of sums form; again is their a clever way to obtain such a form; Option 4 SELECT DISTINCT pc1.persid FROM perscolor pc1 INNER JOIN perscolor pc2 ON pc1.persid=pc2.persid AND pc2.colorid=2 INNER JOIN persmaterial pm1 ON pc1.persid=pm1.persid AND pm1.materialid=2 LEFT OUTER JOIN perscolor pc3 ON pc1.persid=pc3.persid AND pc3.colorid=1 LEFT OUTER JOIN perscolor pc4 ON pc1.persid=pc4.persid AND pc4.colorid=3 WHERE COALESCE(pc3.persid,pc4.persid) IS NOT NULL Remarks: *this option requires the pseudo query to be turned into a product of sums form Option 5: SELECT p.persid FROM person p, persmaterial pm,perscolor pc1,perscolor pc2,perscolor pc3 WHERE p.persid=pm.persid AND p.persid=pc1.persid AND p.persid=pc2.persid AND p.persid=pc3.persid AND (pc1.colorid=1 OR pc2.colorid=3) AND pc3.colorid=2 AND pm.materialid=2 GROUP BY p.persid Remarks: *very easy to get from pseudo query to MySQL query but what about performance? -- phpMyAdmin SQL Dump -- version 2.6.1 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Oct 19, 2006 at 01:13 PM -- Server version: 4.1.9 -- PHP Version: 4.3.10 -- -- Database: `aston` -- -- -------------------------------------------------------- -- -- Table structure for table `color` -- CREATE TABLE `color` ( `colorid` int(11) NOT NULL auto_increment, `color` varchar(30) NOT NULL default '', PRIMARY KEY (`colorid`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ; -- -- Dumping data for table `color` -- INSERT INTO `color` VALUES (1, 'red'); INSERT INTO `color` VALUES (2, 'green'); INSERT INTO `color` VALUES (3, 'blue'); INSERT INTO `color` VALUES (4, 'yellow'); -- -------------------------------------------------------- -- -- Table structure for table `material` -- CREATE TABLE `material` ( `materialid` int(11) NOT NULL auto_increment, `material` varchar(30) NOT NULL default '', PRIMARY KEY (`materialid`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; -- -- Dumping data for table `material` -- INSERT INTO `material` VALUES (1, 'wood'); INSERT INTO `material` VALUES (2, 'iron'); -- -------------------------------------------------------- -- -- Table structure for table `perscolor` -- CREATE TABLE `perscolor` ( `perscolorid` int(11) NOT NULL auto_increment, `persid` int(11) NOT NULL default Ɔ', `colorid` int(11) NOT NULL default Ɔ', PRIMARY KEY (`perscolorid`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ; -- -- Dumping data for table `perscolor` -- INSERT INTO `perscolor` VALUES (1, 1, 1); INSERT INTO `perscolor` VALUES (2, 1, 2); INSERT INTO `perscolor` VALUES (3, 2, 1); INSERT INTO `perscolor` VALUES (5, 3, 3); INSERT INTO `perscolor` VALUES (6, 3, 2); -- -------------------------------------------------------- -- -- Table structure for table `persmaterial` -- CREATE TABLE `persmaterial` ( `persmatid` int(11) NOT NULL auto_increment, `persid` int(11) NOT NULL default Ɔ', `materialid` int(11) NOT NULL default Ɔ', PRIMARY KEY (`persmatid`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ; -- -- Dumping data for table `persmaterial` -- INSERT INTO `persmaterial` VALUES (1, 1, 1); INSERT INTO `persmaterial` VALUES (2, 1, 2); INSERT INTO `persmaterial` VALUES (3, 2, 1); INSERT INTO `persmaterial` VALUES (5, 3, 2); -- -------------------------------------------------------- -- -- Table structure for table `person` -- CREATE TABLE `person` ( `persid` int(11) NOT NULL auto_increment, `name` varchar(30) NOT NULL default '', PRIMARY KEY (`persid`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ; -- -- Dumping data for table `person` -- INSERT INTO `person` VALUES (1, 'john'); INSERT INTO `person` VALUES (2, 'emily'); INSERT INTO `person` VALUES (3, 'liz');
Simple Sql Question: Using A Query Result As A Query Variable
EDIT: it works now, I had an error in my code, not my method. I have a very simple question. I have 2 tables: 'users' and 'posts' with the following structure: users: id, username, email_address posts: id, user_id, post_title, post_text in a my own mind's mysql, I would like to: SELECT posts.id, posts.user_id, posts.post_title, posts.post_text users.username FROM users, posts WHERE posts.user_id = users.id I usually do one query for the post data, and then, based on the use_id record, do another of the users table, but today, I'm being forced to do them in one swoop.
Query Based On Results Of A Previous Query
So far I have managed to construct one query which gives me all individuals that have one of three titles. based on this I now want to find all the individuals that are affiliated to those listed in the first query ....
Big Query - Query Not Completely Stored In Memory
I have this query and when executed in mySQL query window throws error that "Big Query - Query not completely stored in memory". Also executed thru app, the program justs hangs. I have checked all indexes, they all look good.....
How Many Rows?
I've a query as below, where i need to get the number of rows it produces that is the count of number of rows. Plz help . Select * from audio left join video on (audio_sid=video_sid and audio_prgm_num=video_prgm_num) left join pcr_info p on (audio_sid=pcr_sid and audio_prgm_num=pcr_prgm_num) right join stream s on (stream_id=audio_sid) where audio_type = 'MPEGLayer1' and isnull(video_type) group by stream_name order by stream_name
Sum Rows But The Max
I'm trying to create a query that calculates the sum of a bunch of rows then return the max (or the highest) value of those sums. So for example I have a table called imgarchives with a field called LinkBacks. I want to do SELECT SUM(LinkBacks) FROM imgarchives ORDER BY LinkBacks DESC LIMIT 0,1 The trouble with that is that I'm not looking for a sum of ALL the columns, I want to create a sum for all the archives based on BlogID. I was thinking GROUP BY might be necessary but I'm not sure how to use that with SUM(). My thoughts are: SELECT SUM(LinkBacks) FROM imgarchives GROUP BY BlogID ORDER BY LinkBacks DESC LIMIT 0,1 That doesn't seem to work. -_- ack.
Add Of Rows
i have a table with data (time[int] und output[int]). I need a column in that the difference between the previous measurement and the current measurement is inside.
|