How To Rewrite This Query Without A Subquery ?
For speed reasons, I would like to rewrite the following query without the subquery: ...
View Complete Forum Thread with Replies
Sponsored Links:
Related Messages:
How Do I Rewrite A Slow Subquery Into A Fast Join? (Prolly Real Easy For A Non-noob To Answer)
I used subquerys because they made more sense to me, until the table got "a lot" of data in it (not really... just 1000 entries) - then all querys including subquerys slowed down to 4-5 secs EACH!! :) This is insanely slow. What I am doing here below is looking into what messages a user has already read in the subquery, so that none of the ones he already has read will EVER again show up for him. So, how do I rewrite this subquery: NOT IN (SELECT reffen FROM $readt WHERE sender = $nr) From this entire SELECT: SELECT halfref, brokensms, DATE_FORMAT(arrived, '%y'), DATE_FORMAT(arrived, '%m'), DATE_FORMAT(arrived, '%d'), DATE_FORMAT(arrived, '%H'), DATE_FORMAT(arrived, '%i'), priv FROM $halft WHERE sender = $nr and halfref NOT IN (SELECT reffen FROM $readt WHERE sender = $nr) order by id desc limit 1 Into a faster join of some sort? I'd aprichiate if you told me what each part of the rewrite actually does, because I been reading about joins for a day now and still don't get them at all!
View Replies !
View Related
Redesigned Table...can't Rewrite Query.
I've just altered the structure of a table in my database to make it clearer, and to remove duplicate records that would have been stored in it. The problem is I now want to query it, and can't work out how to do it in one query. I could do it in 3, but I'd rather be efficient if possible. The table structure is class classid - int(3) - auto increment - primary key classname - varchar(25) classparent - int(3) The idea being that a record from another table is linked to a classid, from which we can extract the parents of that particular class. There could be varying number of levels, but the top level has a classparent of 0. Is there a way of writing this into one query, ie. using a classid, select the values for that row, and its parent, grandparent etc.?
View Replies !
View Related
Subquery With Range Query
I have one table with user id and login hour. So I want to make a query that select one user(example WHERE ID = 2) together with the range (BETWEEN 10 AND 50), so my question is how do I combine the two SQL condition into one SQL statement and I know subquery will be involve but I did not know how to write....
View Replies !
View Related
I Need Help With A Query/subquery Tangle
I started out trying to do everything at once and really ran into problems (5 tables! my head hurts), so i broke the original query in half to get: $query ="SELECT members.id, members.lname, members.fname, member_email.email, member_phone.phone, committees.id, committees.name, committees.description, committees.chair_id, committees.staff_id, staff.phone, staff.email, staff.id, staff.name FROM committees, staff, members, member_email, member_phone WHERE committees.name='Test' AND members.email_id=member_email.id AND members.phone_id=member_phone.id AND staff.id=committees.staff_id AND members.id=committees.chair_id"; //ORDER BY members.lname DESC $result= mysql_query($query) or die ("could not retrieve information"); ............
View Replies !
View Related
Optimize UPDATE Query With Subquery
Users(users_id,...,pictures_average_grade) - 5,000 rows Pictures(..,average_grade,users_fk) - 50,000 rows One User can have many pictures. Each picture have average_grade which is being continually changed. Once a day i would like to compute for each user average grade of his pictures and update column. users.pictures_average_grade. I wrote the following query: UPDATE users AS u SET u.pictures_average_grade= (SELECT AVG(average_grade) FROM pictures WHERE users_fk=u.users_id). The problem is that the query is being processing very long (after 15 minutes i resing and stop the query).
View Replies !
View Related
Need To Use Same Table In Subquery As In Insert Query
I have this table called "testtab": ID | value ---------- 1 | 8 2 | 15 3 | 5 Field ID is INT autoincrement as usual for ID field, field value is common INT. I need to insert new record to it. The inserted value should be equal to the highest value +1. I tried to do something like this: INSERT INTO testtab SET value=(select max(value) from testtab)+1 Mysql threw this error: You can't specify target table for update in FROM clause I searched internet and found that I cannot use the same table in a subqery of insert/delete/update query. So my question is: Is here some workaround for this? I know I could use two queries - one to find the maximum value and second to insert the value+1 into DB, but I would like to do it in a single query.
View Replies !
View Related
Question W/ SELECT Query - Need A Subquery?
I have 2 tables: *user - each row is a user *interest - each row is a relation between a user and an interest I am trying to construct a query to determine all other users that share overlapping interests; and also report the total number of interests these users have. I am having diffculty extracting the part in bold. The following query will extract everything, but the part in bold: Quote: SELECT DISTINCTROW *, count(u.userid) AS matches FROM interest f1, user u WHERE f1.userid=u.userid AND f1.interestID IN ($qstr) GROUP BY f1.userid ORDER BY matches DESC LIMIT 0,10 note that $qstr contains a list of all interest IDs that the reported users must share. I have now built the following query, which doesn't work: Quote: SELECT DISTINCTROW *, count(u.userid) AS matches, count(f2.interestID) AS denom FROM interest f1, user u, interest f2 WHERE f1.userid=u.userid AND f1.interestID IN ($qstr) AND f1.userid=f2.userid GROUP BY f1.userid, f2.userid ORDER BY matches DESC, denom DESC LIMIT 0,1
View Replies !
View Related
Query With Row Being Used To Identify Database In A Subquery
- FOODS - id | food 1 | taco 2 | burrito and the following tables named taco and burrito - TACO - id | food_name 1 | soft taco 2 | hard taco - BURRITO - id | food_name 1 | fried burrito 2 | super good burrito I want to be able to create a query that will select the id from foods and then use the food row to determine which database to use in a subquery. select id, (select food_name from taco.my_food) from foods; The taco part that is red in the query above is where i need to pull the reference from the foods table in the food row. (please keep in mind this is a super generalized version of the query, so there are no where statements,
View Replies !
View Related
Alias To Outer Query In Subquery
I have been using a query on MySQL 5.0.51a and it has been fine. Today my host has upgraded to 5.0.67 and now the query no longer works. I have had a quick look over the changelog and it looks like MySQL should not have allowed an alias in the subquery to reference the outer query in the first place. So now I am stuck in finding a solution to re-writing the query without needing the alias. The query will get the current weeks game fixtures and check to see if the user has any predictions left to add for that week. If you need to see the structure of my tables, just let me know! SQL Code:....
View Replies !
View Related
Rewrite
How can I write this query so it works on mysql 3.54: ++++++++++++++++++++ select groupmembers.memberid,users.name from groupmembers,users where (not users.name='root') and groupmembers.groupid=(select groups.id from groups where groups.type='Privileged') and groupmembers.memberid=users.id order by name ++++++++++++++++++++ And, it it possible to remove the case sensetivity of table names
View Replies !
View Related
How To Rewrite This Without Subqueries?
i have a table that contains the fields order_id, canceled, and captured. the same order_id can appear many times in the table. i want to retrieve all the order_ids for which NO record exists that has both canceled and captured = N. i am not able to upgrade my version of mysql at the moment, so i would like to write a query that does that with no subqueries.
View Replies !
View Related
How Can I Rewrite This Join In Mysql 3.2?
I am trying to select all the fields from ACS and at the same time check if in ACC there is a certain link to another table. This should be expressed in the counter field. However, the query below doe not work as it only selects ACS rows without any link in ACC (is null) or ones with a link through to ACT. Here is the sql: SELECT `ACS` . * , COUNT( `ACC`.`ID` ) counter FROM `ACS` LEFT JOIN `ACC` ON `ACS`.`ID` = `ACC`.`ACS_ID` WHERE `ACC`.`ID` IS NULL OR `ACC`.`ACT_ID` = "480" GROUP BY `ACS`.`ID` ORDER BY counter DESC , `NAM` ACC has the following fields: ACS_ID = link to ACS ACT_ID = link to ACT Right now, it only give me 13 rows - while ACS has about fifty rows in it.
View Replies !
View Related
SUBQUERY Vs DEPENDENT SUBQUERY
I have a table called `accounts`, that contains columns: account_name VARCHAR (128) account_no VARCHAR (16) account_hash VARCHAR (32) balance DECIMAL(10,2) There is an INDEX on account_hash and there's currently 128 rows in the table. I have a table called `activity` that contains columns:....
View Replies !
View Related
Subquery Or Correlated Subquery Help
I need to develop a sql that uses the results from the first Query to find data in the second Query. Then the results of the second query to find the final results of the third Query. I’m also wondering if I should try to just link all these tables together instead of Subqueries or Correlated Query. First Query select ACCOUNT_ID, ACCOUNT_TYPE_C, PAT_ID from PAT_ACCT_CVG where ACCOUNT_TYPE_C in (120103,120104,120101) Second Query SELECT PAT_CVG_FILE_ORDER.PAT_ID, PAT_CVG_FILE_ORDER.LINE, COVERAGE.COVERAGE_ID, COVERAGE.CVG_EFF_DT, COVERAGE.CVG_TERM_DT FROMPAT_CVG_FILE_ORDER LEFT OUTER JOIN COVERAGE ONCOVERAGE.COVERAGE_ID = PAT_CVG_FILE_ORDER.COVERAGE_ID Where coverage.payor_id = ?' Third Query select TRAN.ORIG_SERVICE_DATE TRAN.TRAN_TYPE, TRAN.INSURANCE_AMOUNT from Tran where TRAN.TRAN_TYPE = 1 and TRAN.INSURANCE_AMOUNT > 0 and TRAN.proc_ID in 1008,1009 (now I need to compare the dates on this query to make sure that the TRAN.ORIG_SERVICE_DATE is within the COVERAGE.CVG_EFF_DT, COVERAGE.CVG_TERM_DT ( dates of the second query)
View Replies !
View Related
Sum() And Subquery
SELECT domainTable.name as domain, sum(NetworkTraffic.upload) as Upload, sum(NetworkTraffic.download) as Download, sum(NetworkTraffic.upload) as Upload2 sum(NetworkTraffic.download) as Download2 FROM `NetworkTraffic` LEFT JOIN domainTable ON domainTable.domainId = NetworkTraffic.domainId WHERE NetworkTraffic.protId=2 AND date between "2005-10-11" AND "2005-10-18" GROUP BY domainTable.name I am using the left-join above to merge two tables (NetworkTraffic and domaintable) on domainId to find which domain to present. By doing this i summarize the download and upload from NetworkTraffic between 2005-10-11 and 2005-10-18, however i want to be able to summarize the traffic from one day, say 2005-10-12 in column 3 and 4 (Download2, Upload2). Is it possible to make a subquery in the sum-function or should i take another approach? I am using mysql server 4.0.18-max-debug
View Replies !
View Related
LIKE ANY + Subquery
I'm trying to get the following statement to work: SELECT * FROM discountItems di WHERE di.name LIKE ANY (SELECT lsw.word FROM ifDefinedSearchWords dsw join ifLinkedSearchWords lsw on lsw.fIFEntityID = dsw.fIFEntityID WHERE dsw.word like 'schoggi') It is supposed to find some words in a subquery as one row, and then search another table for records matching any of those words. I get the following error message: #1064 - 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 .....
View Replies !
View Related
Subquery Help
I am using mysql 4.0 which does not support subquerys.How can i rewrite the below query using joins for mysql 4.0 select * from t1 where t1.eid not in(select eid from t2)
View Replies !
View Related
Subquery Help.
I am using the following but then I rembered I am getting the readyPrinted_id from the select statement!! How can I fix it so it gets the readyPrinted_id and then performs the AND with that same ID? SELECT `sub_name` , `readyPrinted_name` , `readyPrinted_id` FROM sub s, readyPrinted r WHERE s.sub_id = $sub_id AND s.readyPrinted_id = r.readyPrinted_id AND r.readyPrinted_id = readyPrinted_id
View Replies !
View Related
Request Help For Subquery
I have a table that records targets and the time it appears on a display. What I would like to do is to report the time difference for each individual target from the initial appearance to the subsequent one, and the time difference from the subsequent one to the next, and so on. So how do I put these these all together to produce one query: for each "select distinct target from display" for number of rows -1 with target "select timeX - timeY from (subquery for distinct target) where (X,Y = subsequent, initial times)"
View Replies !
View Related
How To Do A Subquery With MySQL 4.0 ?
I couldn;t upgrade to mysql 4.1 for some reason, so I am forced to use mysql 4.0. I try to change my database from pgSQl to mySQL. But the proble is how to make a query like : "SELECT field FROM table WHERE (select count(*) from table2)<5 " which is very easy under pgSQL but not allowed under mysql because the subqueries seem not to be allowed...
View Replies !
View Related
Subquery (not Exists)
I've got some sort of syntax problem that doesn't seem to make a lot of sense. I'm developing a Categories Theory application and because of that I need to make big, and by "big" I mean HORRIBLY HUGE queries. That one has 54 lines and 3 subqueries (only the first one is shown so that I won't scare people off :)). The thing is, I don't seem to be getting the hang of how to do subqueries. The syntax seems fine... But it'll still always say the same thing: 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 'exists ( select * from objeto c, morfismo f1, morfismo f2 (It's MySQL 4.0.11a-gamma) The only difference I see between the code below and the mysql.com documentation is that my subqueries aren't alone in their "where" clauses... Aside from that, they seem pretty much okay. Am I missing something?.....
View Replies !
View Related
Correlated Subquery
SELECT MAX(e1.score) AS high_score , e1.dept , (SELECT e2.emp_no FROM Employee_Evaluations AS e2 WHERE e2.dept = e1.dept AND e2.score = MAX(e1.score)) AS emp_no FROM Employee_Evaluations AS e1 GROUP BY e1.dept It doesn't work in MySQL (I've tried 4.1 and 5.0), but it seems like it should work and if I'm not mistaken, it's valid SQL99. Can anyone confirm this? I don't need help writing a compatible version, I've already done that - just curious if this little bugger is standards compliant.
View Replies !
View Related
Slow Subquery
Can anyone tell me why the following query with sub-query takes forever to finish? (I've le it run for 20 minutes, and it still hasn't finished) select date from temps where date in (select distinct date from observations where camera like "a") The sub query returns 10 dates. The outer query is on a table that contains about 40,000 rows. What's the big deal here? All I'm trying to do is select rows from "temps" that match a small range of 10 dates. Is there another way to do this? Is a sub-query the wrong approach?
View Replies !
View Related
Subquery As Join
I have the following query, which works perfectly on my developpement computer: UPDATE writings SET num_votes=(SELECT COUNT(vote) FROM votes WHERE writing_id=id), rating=(SELECT AVG(vote) FROM votes WHERE writing_id=id); Unfortunately, my host doesn't seem to allow subqueries. Is there a way to do this with joins? I've heard that joins are faster anyhow.
View Replies !
View Related
Subquery Issue
I have a query at sql.pastebin.com/d3398502e and it's a bit of a monster (sorry, it says I can't post the actual link because I'm a new user, I assume it's a spam precaution, so please copy and paste). It's a search query for a hotel site, like expedia, but it needs the ability to get different prices for children in a room based on their age. Each hotel can have age groups, so it needs to figure out how many children are in each age group for that hotel (which works, that's all the UNIONs), and then apply the price associated with that age group to the number of children for that hotel for that date. That's where I'm stuck since the price data for that date is not available in the subquery. The way I have it now it's selecting all dates that have child prices applied and adding those together, rather than just the one date.
View Replies !
View Related
Subquery To JOIN
SQL Code: Original - SQL Code SELECT COUNT(*) FROM `cmn_group` AS `g` INNER JOIN `cmn_company` AS `c` ON g.cmn_company_id = c.cmn_company_id WHERE g.cmn_group_id !=5 AND g.group_name = 'G4' AND g.cmn_company_id = ( SELECT cmn_company_id FROM cmn_group WHERE cmn_group_id =5 )  SELECT COUNT(*)FROM `cmn_group` AS `g`INNER JOIN `cmn_company` AS `c` ON g.cmn_company_id = c.cmn_company_idWHERE g.cmn_group_id !=5AND g.group_name = 'G4'AND g.cmn_company_id =( SELECT cmn_company_id FROM cmn_group WHERE cmn_group_id =5)
View Replies !
View Related
Using Limit In Subquery
I am trying to use Limit in a subquery but receive an error. Is there another way to archive the same end result without Limit? SELECT * FROM news WHERE news.id NOT IN (SELECT news.id FROM news ORDER BY date DESC LIMIT 15) Error: #1235 - This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'
View Replies !
View Related
Update With Subquery?
I have two tables and I want to update one with data from the other TableA id description date TableB id counter date I want to update counter in TableB with its current value minus a count from tableA UPDATE TableB set counter = counter - (SELECT count(id) WHERE description = 'blabla') But I only want to do this on the date columns are equal. For example date in TableB is 2007-03-13, and counter should be updated with its value minus the selection from TableA where date is the same. But I want to do this on all rows for all dates in one query. How do I do that? Add a where to the subquery ie "WHERE TableB.date = TableA.date"? Is that correct?
View Replies !
View Related
SubQuery To Add A Column
I have the following SQL which is the best I can do to illustrate what I am trying to accomplish: select column_name as 'name', column_default as 'default', column_type as 'type', (select column_name from maillists where listname="winserver") as 'data' from information_schema.columns where table_name='maillists'; Essentially, I am trying to get a "description" of my table along with an additional column of the current value for each field in the table. What I am getting instead is a repeat of the column name in the data column....
View Replies !
View Related
Subquery In COUNT()
I have table with names and ages of peoples. I need to select ALL names and number of younges peoples. name|age aaa |30 bbb |31 ccc |32 eee |32 result: aaa |0 bbb |1 ccc |2 eee |2 I try use: SELECT T1.name, COUNT(SELECT * FROM tablename AS T2 WHERE T2.age<T1.age) FROM tablename AS T1; But error in syntax :(
View Replies !
View Related
Error While AVG On A Subquery
I have a ticket_audit_log table that is a list of changes done on tickets in the ticket table. Every change is a timestamp, so i can select the min and max timestamp for each ticket change and calculate the difference that is the time the ticket has been worked on. The query I use is: ....
View Replies !
View Related
Using IN With An Empty SUBQUERY
UPDATE bb_topics SET topic_status = 1 WHERE topic_id IN (SELECT topic_id FROM bb_topics WHERE forum_id = 1 AND topic_start_time < DATE_SUB(CURDATE(), INTERVAL 30 DAY) AND topic_status = 0); If the subquery returns an empty dataset I get a syntax error. Is there any way to test if the subquery is null or exist. I have tried EXISTS and IFNULL with no success.
View Replies !
View Related
Subquery Using Limit
I am trying to use a limit 1 in a subquery which its returning a error saying its not supported. Basically I have a table for Locations where equipment has been and I need to run one query that returns only the last location that the equipment has been. The below query is returning any of the ID numbers where the current location = 232. This does return results but it also returns results where 232 is one of the previous locations. A simple fix would be to use LIMIT 1 in the subquery but since that isnt supported .....
View Replies !
View Related
Subquery As An Array?
Let us say I have two tables: - user: userid, username - post: postid, userid In a single query, given the "userid" value, I want to select "username" from the user table, and select all postid values from the post value where the userid="myuserid". Something like... SELECT username, (SELECT postid FROM post WHERE userid="myuserid") AS postids FROM user WHERE userid="myuserid" I'm sure you can spot the problem--the subquery returns more than one row of data. Is there any way I can make "postids" be an array, or a comma-separated list, or something like that?
View Replies !
View Related
Subquery With IN Clause
I have a table full of subscriptions to a service. this is our second year, and i want to see how many people returned for a new season. I am having a hard time finding a solution to this problem. so far i have this... SELECT count(*) FROM product WHERE DATE_FORMAT(insert_date,"%Y")='2005' AND payer_email IN (SELECT DISTINCT payer_email FROM product WHERE DATE_FORMAT(insert_date,'%Y')='2004') but the page just never loads when i run that. Does anyone have any ideas as to what's wrong with my query, or a better query i might make?
View Replies !
View Related
DELETE And Subquery
Here is my DELETE statement that should work but doesn't due to "Currently, you cannot delete from a table and select from the same table in a subquery. " DELETE FROM history WHERE eventTime = (SELECT MIN(eventTime) from history) I found information about selecting the max with a subquery here:
View Replies !
View Related
MySQL Subquery Using NOT IN
I need a little help rewriting a subquery in a MySQL db that does not support this type of query. I have read the manual about how to convert a NOT IN to a left join and it makes good sense, but I have on small addition to it that I cannot get to work. The manual states that this is the correct SQL for a NOT IN subquery:
View Replies !
View Related
Row Subquery In Fieldlist
I am trying to figure out how to shorten my SQL. I know I can do this: SELECT (SELECT some_single_field FROM somewhere) AS field_alias FROM parent_table But I want to be able to use the subquery to return 2 values - something like this, (pseudo-code): (SELECT some_field, some_other_field FROM somwhere) AS field_1, field_2 I know how to do comparisons in the WHERE clause using multiple columns, but I can't seem to figure it out in the beginning of the select. Does anyone know how this is done?
View Replies !
View Related
Using Union In A Subquery?
I'm trying to make a query that fetches messages that were created by one of your friends (friendships are stored in a separate table) and was thinking this query would possibly do the trick: SELECT * FROM public_messages WHERE author_id IN ( (SELECT friend_from FROM friendships WHERE friend_to=1 AND pending=0) UNION (SELECT from_to FROM friendships WHERE friend_from=1 AND pending=0) ) Where the user's id is 1... Running this query gives an error of: #1064 - 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 'UNION ( SELECT from_to FROM friendships WHERE friend_from = 1 AND pending = 0 ) ' at line 1 and of course it works fine without the union... Is such a thing possible in one query?
View Replies !
View Related
Making The Right Subquery
I've been trying to wrap my head around this one for a while, and while it would be pretty easy to do using a loop in PHP I'd like to keep it in a single SQL statement if possible. I have a table of comments, very much like you would store comments in for a blog. It goes something like this: idCOMMENT | FK_LIST_ID | COM_Posted | COM_Comment autoincrement| foreign key of post | Timestamp | Text for Comment I only want to keep the most recent 30 or so comments on each listing so I need to create a statement that will delete any excess comments. I could loop a statement like this in PHP: DELETE FROM COMMENT WHERE idCOMMENT IN (SELECT idCOMMENT FROM COMMENT WHERE FK_LIST_ID=(variable from PHP) ORDER BY COM_Posted Desc LIMIT 30, 10^10) But there will be thousands of listings, (it's and that's going to be rough on the server to make thousands of calls to it each night with the maintenance script. I think there must be a way to do this in pure SQL, just send one SQL statement to the server and that's it, but can't figure it out. Can you point me in the right direction?
View Replies !
View Related
|