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 Complete Forum Thread with Replies
See Related Forum Messages: Follow the Links Below to View Complete Thread
Subquery Or Join ?
I've got two tables First has ID,Name,Descr Second: ID,IDFirst,Price,ChangeDate in first i've got some products, in second i've got a prices for that products (one product can have more than one price - 'cause i'm using it in another tables) i'd like to show products list with most the newest price. is this possible without subquery?
Need Help Converting Subquery Into Join
I need a bit help, Table structure Member ------ id Registration ------------ id meeting_id member_id Using subQuery: Select m.* from member m where m.id NOT IN ( select r.member_id from Registration where meeting_id != XXX ) Since I'm using old version of mysql v4.0 which doesnt support subquery, so that query above wont work. Is there anyway I can rewrite that query above using (JOIN?) .. and make it work? I tried Select m.* from member m left join registration r on m.id = r.member_id where r.id is null and r.meeting_id != XXX It doesnt work because of the meeting_id constraint.
Which One? JOIN, Subquery, UNION?
I am having trouble with a select statement. Here's what I want to do: tbl1 is a list of photo albums, each with an 'album_id'. tbl2 is a list of photos, with a column specifying the 'album_id' of the photo album it belongs to. I want to SELECT a list of albums, and append to that list a column containing the number of photos in that particular album (determined by counting the number of photos that have an 'album_id' matching each album). How should I do this?
Help With LEFT JOIN & Subquery
It seems my original plan for this query doesn't work, and I'm not sure how to change it so that it would. Any ideas? I don't think much detail is needed about the tables (if so let me know and I'll post up more info) - I basically just want to do a left join of one table with a subquery (another table, but only rows with group_id=3). Since I'm working with MySQL 4 views/stored procs aren't an option. Is my syntax just wrong, or do I need to approach this issue differently? My original query: SELECT * FROM modules LEFT JOIN (SELECT * FROM permissions WHERE permissions.group_id = 3) AS perm ON modules.id = perm.module_id
Convert Subquery To JOIN
I have a working subquery:Code: SELECT ID, company_name, logo_file_name FROM company ORDER BY (SELECT 1 FROM company as inside WHERE TRIM(logo_file_name) != '' AND ID = company.ID) DESC, company_name ASC It grabs all of the company rows, and puts the ones that have a logo file name at the top.This query works fine on my testing machine (mysql 4.1.7). However, my production machine only has mysql 4.0.18 and I have no way of upgrading it to 4.1 to get subquery support. I've been looking at trying to convert it using a JOIN statement, but I'm stumped.
Can You Left Join A Subquery In The WHERE Clause?
I am having difficulty with a fairly complex query. I want to LEFT JOIN a subquery in the where clause like this GREATLY simplified example: SELECT t1.field1, t2.field2 FROM table1 t1, LEFT JOIN (select field2 FROM table2 WHERE field3=22) as t2 on t1.id = t2.t1_id Using MySQL 4.1
JOIN/Subquery Nightmare... Please Try Your Hand At It!
Let's say you have three tables - colors, items, and item_display: colors: +----+---------+ | id | name | +----+---------+ | 1 | red | | 2 | green | | 3 | blue | +----+---------+ items: +----+-----------+-------+ | id | colors_id | name | +----+-----------+-------+ | 1 | 2 | grass | | 2 | 1 | apple | | 3 | 2 | apple | | 4 | 3 | sky | | 5 | | glass | +----+-----------+-------+ item_display: +----+---------+----------+-----------------------------------+ | id | item_id | item_id2 | description | +----+---------+----------+-----------------------------------+ | 1 | 1 | | The grass is green | | 2 | 2 | 3 | Both apples, but different colors | | 3 | 4 | | Sky is blue during the day | | 4 | 5 | | We'll say the glass is colorless! | +----+---------+----------+-----------------------------------+ .SQL file here: http://dev.soulpass.com/sample.sql Here is the desired output from the final query: +----+--------+--------+-------+-----------------------------------+ | id | color1 | color2 | name | description | +----+--------+--------+-------+-----------------------------------+ | 1 | green | | grass | The grass is green | | 2 | red | green | apple | Both apples, but different colors | | 3 | blue | | sky | Sky is blue during the day | | 4 | | | glass | We'll say the glass is colorless! | +----+--------+--------+-------+-----------------------------------+ The fun stuff: Since some items (e.g. - glass) will not have any color, there will need to be an outer join between colors and items. The following query takes care of that, but does not extract the second color for records that have a second color (e.g. - apples): SELECT item_display.id, colors.name AS color1, items.name, item_display.description FROM item_display, items LEFT OUTER JOIN colors ON items.colors_id = colors.id WHERE item_display.item_id = items.id; +----+--------+-------+-----------------------------------+ | id | color1 | name | description | +----+--------+-------+-----------------------------------+ | 1 | green | grass | The grass is green | | 2 | red | apple | Both apples, but different colors | | 3 | blue | sky | Sky is blue during the day | | 4 | | glass | We'll say the glass is colorless! | +----+--------+-------+-----------------------------------+ I think that extracting the second color will require a subquery. Here is an example of what *looks* right to me, but does not work: SELECT item_display.id, colors.name AS color1, (SELECT colors.name FROM colors, items, item_display WHERE items.colors_id = colors.id AND item_display.item_id = items.id) AS color2, items.name, item_display.description FROM item_display, items LEFT OUTER JOIN colors ON items.colors_id = colors.id WHERE item_display.item_id = items.id; The reason it doesn't work is because the "Subquery returns more than 1 row" (to quote the error). Sooo, I think the only way to get it to work would be to somehow "tell" the subquery what the current item.id is for the parent query. Hopefully this whole thing makes sense, but more examples and information can be provided. I think the example tables are set up the way the need to be, but I am certainly open to structural suggestions. The item_display table is purposefully linking items together rather than directly linking colors. For the sake of this example, a "red apple" is totally different from a "green apple," but they are similar enough to warrant a link when displaying all of the items along with descriptions.
Problem With Subquery And Join Between Two Tables
I have two tables, the first is the user table (the user is unique) and the second table of experience job (the user can have more than one experience job). I need to do a SQL query where it shows the data of the user (tabal of user) and single a experience job (the one last), my problem is that I have not been able to do the query, my query shows me all the experience job of the user, but I need the one last. I have the following query, but the problem is that it shows null the experience job column from the second user in ahead.....
Workaround For Outer Join Using Filtering Subquery
I'm using mysql 4.0.x, which does not allow the following query (which works fine in 4.1). Is there any way I can issue a single query to achieve the same results? (I want a list of all records from table al, nulled where there is no match in table alm, which has been filtered. Without a subquery, the filtering occurs after the outer join, and for one specific row from alm, I only see the nonmatching records from al where NO other alm record matches.) SELECT al.id, alm.idmember, al.listname FROM addresslists AS al LEFT OUTER JOIN (SELECT idlist, idmember FROM addresslistmembers WHERE idmember = 4) AS alm ON al.id = alm.idlist
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!
How To Get The SUM Value From Two Tables? Join Tables? Subquery?
Hi, I have two tables: table A Id. | id_result | value 1 | 1| 10 2 | 1| 11 3 | 2| 7 4 | 2| 13 table B Id. | id_result | value 1 | 1| 4 2 | 1| 1 3 | 2| 5 4 | 2| 6 How can I get sum of unique keys from table A and B (id_result) like this?: id_result | sum_table_A | sum_table_B 1 | 21| 5 2 | 20| 11 I can do it with UNION or 2 separate SQL statement, but how to make it in 1 query or using subquery?
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. Im 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)
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)
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
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 .....
Subquery
Hi, wanted to use a subquery, as in: SELECT * FROM pending WHERE username = (SELECT username FROM ratings); But have learned subqueries are only available in MySQL 4.21 or later... So... I've tried to use the following query: Code: SELECT ratings.username,pending.username FROM ratings,pending WHERE ratings.username="jjfjunk" OR pending.username="jjfjunk"; But this returns an empty set, even though I know that the username exists in the ratings table.
Subquery
Can help to find any sytanx error from the following command? select IMG_ID FROM image WHERE WORM_Name IN (SELECT WORM_Name FROM worm WHERE WORM_Age='adult') I don't know where is wrong of above, but always got the sytanx error messange after I type in the above commands.
Subquery Help
I am pretty sure I have the syntax totally wrong.. but you can probably get an idea of what I want to do. Code: INSERT INTO library (tape_id,number) VALUES('DDFA3','433145') WHERE DDFA3 NOT IN (select tape_id from library where used = '1')"; I'm basically wanting to make sure that no record for that tape_id exists that is set to "used" before I insert another record.
Subquery
I'm having trouble getting the results I need from an sql query. I believe I can accomplish my task with a subquery however I can't get it to work. I have a table of book titles and a one to many table of books read (that holds many people via ID and the book via ID they read). Now I need to get a list of books left to read by a particular person from my join. So the query starts with a join between the books table and the books read table to get the book titles. I use a left join to get all the book titles even if they haven't been read. However I need it to filter out the books that the particular person has read and leave me with a list of books left to be read by the particular person. Since I'm using a join I need it to ignore the records of the other people so that it will include does books in the results while excluding the books that the particular person has read.
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
LEFT JOIN? RIGHT JOIN? Multiple JOIN?
Simplifying this down to its basics, I'm using LEFT JOIN in a query but I'm not getting the results I want. The tables are: table services service_id service_name table services_provided service_id service_date (date field) cust_id service_quantity I need to select ALL services from the services table, and the number of services provided (by a specific customer, in a specific time frame) from the services_provided table, so that I can generate a list that shows services provided by that customer in the specified period of time The query: SELECT service_date, service_name, service_quantity FROM services LEFT JOIN services_provided ON services_provided.service_id = services.service_id WHERE cust_id = $cust_id AND MONTH(service_date) = 10 AND YEAR(service_date) = 2007 GROUP BY service_id ORDER BY service_id (Aside: The date to be selected varies - it may be the whole year, or may be a selection of months,such as 1, 2 or 3. This is determined dynamically in the script. The cust_id is determined by which customer is logged in.) I'm pretty sure that the left join as I have it should return all services, even if there's no corresponding entry in the services_provided table. But because of the WHERE clause, I don't get a complete list of all services -- if the customer doesn't have any entries for a particular service, that service doesn't come up in my results. Do I need to change how I'm joining the tables, or join them twice? I'm sure I could do this with a nested query, but I'm trying to avoid that.
Join Vs. Inner Join Vs. Implied Join = Different Results ??
I SUM() only on the order table in all queries below. Here's a set of queries that I thought would/should yield the exact same results: QUERY 1: SELECT COUNT( o.orderID ) FROM order o WHERE DATE( o.orderDATE ) = ��-01-04' AND o.orderSTATUS = 300 yields 161 QUERY 2: SELECT COUNT( o.orderID ) FROM order o LEFT OUTER JOIN credit_card cc ON o.orderID = cc.orderID WHERE DATE( o.orderDATE ) = ��-01-04' AND o.orderSTATUS = 300 yields 175 QUERY 3: SELECT COUNT( o.orderID ) FROM order o, credit_card cc WHERE o.orderID = cc.orderID AND DATE( o.orderDATE ) = ��-01-04' AND o.orderSTATUS = 300 yields 157
Yet Another Subquery Question (I Think)
I have done some looking into subqueries on the boards and at mysql.org, but I can not seem to find the answer to my problem. Maybe there is no solution maybe the solution is simple. I have tried to construct a query for this problem, but everytime I do I run into a problem where I don't know where to go next. So, I don't have a query that I have been trying to display.... Problem: With MySQL 4.1.21-standard running I have the following tables; -- -- Table structure for table `users` -- CREATE TABLE `users` ( `USER_ID` int(11) NOT NULL auto_increment, `REGIONAL_ID` smallint(5) NOT NULL default Ɔ', `TEAM_LEADER_ID` smallint(5) NOT NULL default Ɔ', `username` varchar(255) NOT NULL default '', `password` varchar(255) NOT NULL default '', `access_level` smallint(2) NOT NULL default Ɔ', `status` tinyint(1) NOT NULL default Ƈ', `num_logins` int(11) NOT NULL default Ɔ', `type` smallint(2) NOT NULL default Ɔ', `last_accessed` bigint(20) NOT NULL default Ɔ', `last_modified` bigint(20) NOT NULL default Ɔ', `created` bigint(20) NOT NULL default Ɔ', PRIMARY KEY (`USER_ID`), UNIQUE KEY `username` (`username`) ) ENGINE=MyISAM AUTO_INCREMENT=464 DEFAULT CHARSET=latin1 AUTO_INCREMENT=464 ; -- -- Table structure for table `profile_core` -- CREATE TABLE `profile_core` ( `STUDENT_ID` int(11) NOT NULL auto_increment, `AGENT_ID` int(11) NOT NULL default Ɔ', `SUPERVISOR_USER_ID` int(11) NOT NULL default Ɔ', `HOST_ID` int(11) NOT NULL default Ɔ', `SCHOOL_ID` int(11) NOT NULL default Ɔ', `type` enum('Normal','Tuition','Hidden','Pals','Private','Cancelled') NOT NULL default 'Normal', `student_number` varchar(6) NOT NULL default Ɔ', `first_name` varchar(255) NOT NULL default '', `last_name` varchar(255) NOT NULL default '', `city` varchar(255) NOT NULL default '', `nationality` char(2) NOT NULL default '', `gender` char(1) NOT NULL default '', `birthdate` bigint(20) NOT NULL default Ɔ', `is_esl` enum('true','false') NOT NULL default 'false', `may_pay_tuition` enum('No','Yes') NOT NULL default 'No', `archived` char(1) NOT NULL default Ɔ', `archived_date` bigint(20) NOT NULL default Ɔ', `comments` text NOT NULL, `last_modified` bigint(20) NOT NULL default Ɔ', PRIMARY KEY (`STUDENT_ID`), UNIQUE KEY `student_number` (`student_number`) ) ENGINE=MyISAM AUTO_INCREMENT=1442 DEFAULT CHARSET=latin1 AUTO_INCREMENT=1442 ; There are a couple of types of users that you can pull from the users table. Regional Managers, State Managers and Area Coordinators are the ones I am mostly trying to get at. Every Area Coordinator has a State Manager and a Regional Manager identified by TEAM_LEADER_ID, AND REGIONAL_ID in the `users` table. Every State Manager has a Regional Manager (REGIONAL_ID). Every Student has a SUPERVISOR_USER_ID identified in the 'profile_core' table which is a direct relation to the USER_ID of the `users` table. What I want to do is find all of the students that are under a user. It is easy, for me, when we talk about only seeing students that are under a Area Coordinator: SELECT STUDENT_ID, CONCAT(CORE.first_name, ' ', CORE.last_name) AS StudentName FROM `profile_core` AS CORE LEFT JOIN `users` AS USERS ON CORE.SUPERVISOR_USER_ID = USERS.USER_ID WHERE USERS.USER_ID = 1 My problem comes when I want to pull up all of the students that are under a Regional (including all of the students that are under all of the Regionals State Managers and all of the students that are under the State Managers Area Coordinators). I hope that made sense. Is it possible in one query? Or, will it take two?
Simple Subquery
I know the basics of sql but i'm really bad at the joins and everything, so i hope someone can help me out with this. items: +-------+-------+ | it_id | name | +-------+-------+ | 1 | item1 | | 2 | item2 | | 3 | item3 | +-------+-------+ subitems: +----+------+-------+ | id | name | it_id | +----+------+-------+ | 1 | a | 1 | | 2 | b | 1 | | 3 | c | 1 | | 4 | d | 1 | +----+------+-------+ now i tried this in my php PHP $result = mysql_query("SELECT name FROM subitems WHERE it_id in (SELECT it_id from items WHERE name='$name'"); echo '<select name="subitems" class="list">' while ($line = mysql_fetch_array($result , MYSQL_ASSOC)) { foreach ($line as $subitem) { echo '<option value="'.$subitem.'">'.$subitem.'</option>' } } echo '</select>'
Need Help With Subquery Syntax
First, what I want to do: I want records from table1, but only the ones that have a "yes" in columnX in table2 for the same memberID (foreign key). I have two tables: ind1b (indID, memberID, date, ...) and reports (reportID, memberID, okay, date) To select all rows in table ind1b I have this query: $query = "SELECT * FROM ind1b WHERE memberID = '$memberID' ORDER BY datum ASC". But I also need to check in table reports to see if there is a "yes" in column "okay" for the variable $memberID. Multiple rows (with different dates) can be returned. So I added this subquery: $query = "SELECT * FROM ind1b WHERE memberID = '$memberID' IN (SELECT reports.okay FROM reports WHERE reports.okay = 'Yes') ORDER BY ind1b.date ASC"; This query gives no error run through phpMyAdmin – but also returns no records. I think that I need the "date" in there somehow but can't figure out how and where.
Subquery Error
I'm receiving this error: Quote: This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery' Not sure why, I'm running MySQL Version 5.0.41-community-nt with WAMP5. Any suggestions? It's a personal project that I would like to continue developing on localhost.
Subquery And Counting
I have a table called people in my database. it looks like this +----+------+ | id | name | +----+------+ | 2 | bob | | 1 | Jill | | 3 | Jill | | 4 | John | | 5 | Jill | +----+------+ I want to display the distinct name and how many times they are in the table So like this Jill - 3 bob - 1 John - 1 How would I go about doing this. I thought maybe something like this but not to sure [code] SELECT COUNT(name) FROM people WHERE name = (SELECT DISTINCT name FROM people); [code]
Subquery Problem(s)
I have set up a database (MySql 4.1.21) with these tables and rows: players p_id (= player_salary.players_id) team_id div_id conf_id fname lname position status player_salary [1 to many] player_id (= players.p_id) yr amount type Basically, the “players” table holds some information for multiple players, and the “player_salary” table holds a player’s salary for each year of their contract. What I am trying to do is display the players’ names and their total salary across the length of their contracts. So, I decided to throw all the relevant player data from the database into a multidimensional array, and then output it with PHP (5.1.6). Here’s my query and PHP $query = array(); $query[] = 'SELECT DISTINCT *' FROM players, player_salary, (SELECT SUM( amount ) AS salary_total FROM player_salary GROUP BY player_salary.player_id) AS table01GROUP BY players . p_idORDER BY players . lname ASC' $rowSet = array(); for ($i = 0; $i < count($query); $i++) { $result = mysql_query($query[$i],$link) or die(mysql_error()); while ($row = mysql_fetch_assoc($result)) { $rowSet[] = $row; } mysql_free_result($result); } echo '<table>' foreach ($rowSet as $outer_key=>$single_array){ echo '<tr>' echo '<td>'.$rowSet[$outer_key]['lname']. ', '.$rowSet[$outer_key]['fname'].'</td>' echo '<td>'.$rowSet[$outer_key]['salary_total'].'</td>' echo '</tr>' } echo '</table>' And here’s where the problems start. While I can calculate the total salary for Johnny Doe, for some reason that same amount appears for John Doe as well (same with the values for ‘year’ and ‘amount’ ). In reality Johnny Doe’s total salary should be (5,000,000+3,000,000+3,000,000=11,000,000) and John Doe’s salary should be (2,000,000) 2,000,000. Here’s what the array looks like: Array ( [0] => Array ( [p_id] => 1 [team_id] => 14 [div_id] => 2 [conf_id] => 1 [fname] => John [lname] => Doe [position] => F [status] => active [player_id] => 0 [yr] => 2007 [amount] => 5000000 [type] => [salary_total] => 11000000 ) [1] => Array ( [p_id] => 0 [team_id] => 14 [div_id] => 2 [conf_id] => 1 [fname] => Johnny [lname] => Doe [position] => F [status] => active [player_id] => 0 [yr] => 2007 [amount] => 5000000 [type] => [salary_total] => 11000000 ) ) So, I’m wondering if someone can tell me what I’m doing wrong? I’m pretty sure it’s the query because when I try the subquery (SELECT SUM( amount ) AS salary_total FROM player_salary GROUP BY player_salary.player_id) in phpMyAdmin, it works. When I put it all together I get the aforementioned results.
Subquery With Many Results?
So i'm looking for a way to have a query with a subquery, but the subquery returns more than one item. ex. SELECT * FROM menu where parent_id = (SELECT menu_id FROM menu WHERE parent_id = 0) the subquery will return [22,30,33] I would like the top query to execute logically as follows: SELECT * FROM menu where parent_id = 22 OR parent_id = 30 OR parent_id = 33 I can't predict the count of the subquery. I can do this with loops in my php but I have a feeling that it is possible to do this with a single SQL statement (multi subqueries).
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)"
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?.....
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?
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:
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?
Count With Subquery
I've a problem with a count with a 3.23.58 sql version... Here's my sql code (short version and normal version below)...
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?
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...
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?
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:
Select Subquery
I am having difficulty in the following subquery. I keep getting the syntax error at 'SELECT count(*)'. SELECT ID, organization, (SELECT count(*) FROM Invoices WHERE paid = 'N') AS paid FROM clients What I am trying to do is to get a list of clients and also count any unpaid invoices. Does anyone know what I am doing wrong.
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 ...
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....
Subquery Not Working
CODESELECT parexel_staff.name, parexel_skills.skill, parexel_activity.date FROM parexel_staff, parexel_skills, parexel_activity WHERE parexel_staff.name = parexel_activity.name AND parexel_activity.skill = parexel_skills.skill AND parexel_skills.skill = 'CGI' AND CURRENT_DATE > (parexel_activity.date + INTERVAL parexel_skills.retake MONTH) AND parexel_staff.name NOT IN ( SELECT parexel_staff.name FROM parexel_staff, parexel_skills, parexel_activity WHERE parexel_staff.name = parexel_activity.name AND parexel_activity.skill = parexel_skills.skill AND parexel_skills.skill = 'CGI' AND CURRENT_DATE < (parexel_activity.date + INTERVAL parexel_skills.retake MONTH) );
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?
Subquery Count
I have this sql statement where its selecting a bunch of folders from the folder table (userfolders) and then its counting how many messages are in that folder in table (privatemessages) well I need to take this sql statement one step further and grab a column from the privatemessage folder also called pstatus, however you can't use more then 1 column in this subquery below...
Suport Subquery
which mysql version supports subquery? mysql 4.1 supports subquery?
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?
|