I have a funky query that works fine with static data but I need my data to be dynamic. So the static data is like this
SELECT c.my_name, c.my_id, (SELECT count(d.friendship_id) FROM another_table d WHERE d.my_id = 1 AND d.my_friends_id = 2) as count FROM myprofile c WHERE c.my_id = 1;
This returns the data I want like this:
my_name my_id count
parijat 123 1 (OR 0 if the row doesn't exist)
For reference, both another_table.my_id (foreign key), another_table.my_friends_id references myprofile.my_id (primary key). another_table.friendship_id is the primary key here and is auto incremented.
Now the actual question:
I want my subquery to be something like this:
(SELECT count(d.friendship_id) FROM another_table d WHERE d.my_id = 1 AND d.my_friends_id = CURRENT_ROW_ID)
where CURRENT_ROW_MY_ID is the c.my_id that is being selected upon in the main query.
Is this possible and if not, what should my approach be to get the results I need ?
You can do a subquery to get the current auto_increment value for that table:
select auto_increment from information_schema.tables where table_schema = 'you_db_name' and table_name = 'your_table_name'
HTH
Francisco
Sometimes I ask before I have completely explored the option. Just found out that a correlated subquery works fine even in select statements. Here is what I did to get it working:
SELECT c.my_name, c.my_id, (SELECT count(d.friendship_id) FROM another_table d WHERE d.my_id = 1 AND d.my_friends_id = c.my_id) as count FROM myprofile c WHERE c.my_id = 1;
my_id is slightly ambiguous. A better word for it would be profile_id, however dealing with a legacy database ain't fun for sure.
Related
I have a list of ids, and I want to query a mysql table for ids not present in the table.
e.g.
list_of_ids = [1,2,4]
mysql table
id
1
3
5
6
..
Query should return [2,4] because those are the ids not in the table
since we cant view ur code i can only work on asumption
Try this anyway
SELECT id FROM list_of_ids
WHERE id NOT IN (SELECT id
FROM table)
I hope this helps
There is a horrible text-based hack:
SELECT
substr(result,2,length(result)-2) AS notmatched
FROM (
SELECT
#set:=replace(#set,concat(',',id,','),',') AS result
FROM (
select #set:=concat(',',
'1,2,4' -- your list here
,',')
) AS setinit,
tablename --Your tablename here
) AS innerview
ORDER BY LENGTH(result)
LIMIT 1;
If you represent your ids as a derived table, then you can do this directly in SQL:
select list.val
from (select 1 as val union all
select 2 union all
select 4
) list left outer join
t
on t.id = list.val
where t.id is null;
SQL doesn't really have a "list" type, so your question is ambiguous. If you mean a comma separated string, then a text hack might work. If you mean a table, then something like this might work. If you are constructing the SQL statement, I would advise you to go down this route, because it should be more efficient.
Lets say I have a table, myTable, like this:
ID1 Value ID2
1 6.5064 3
2 7.9000 3
3 9.9390 3
4 8.6585 3
What I'm trying to do is SELECT each of those Value's for a given ID2. However, the number of rows returned for Value can change. So, if ID2 = 2, only 1 row might get returned. If drID = 4, 3 rows might get returned.
The part of my query that is trying to handle this is nested, so when I run it I get a "Subquery returns more than 1 row" error. Any idea how I can select a variable number of rows in this way?
Thanks in advance!
Edit: here is what I have so far, and the commented out portion is what I expected to select those values for me, but it throws the above mentioned error:
SELECT drDateTime AS Date,
(SELECT fncName FROM functionlist
WHERE datarecord.fncID = functionlist.fncID) AS FunctionName,
(SELECT alText FROM alarmlevellist
WHERE datarecord.alID = alarmlevellist.alID) AS AlarmDescription
#(SELECT rdValue FROM rawdata
#WHERE datarecord.drID = rawdata.drID)
FROM datarecord
WHERE alID IS NOT NULL AND drSumFlag = 1;
You should show your query.
One common place this problem occurs is in where (or having) clauses. A solution to this problem is to use in rather than =, if the subquery is in the where clause. If you have something like:
where id = (select id2 . . .)
Then change it to:
where id in (select id2 . . .)
Use a join instead of a subquery. I would probably use a join for all tables but that is up to you.
SELECT drDateTime AS Date,
(SELECT fncName FROM functionlist WHERE datarecord.fncID = functionlist.fncID) AS FunctionName,
(SELECT alText FROM alarmlevellist WHERE datarecord.alID = alarmlevellist.alID) AS AlarmDescription,
rawData.drID
FROM datarecord
INNER JOIN rawdata
ON datarecord.drID = rawdata.drID)
WHERE alID IS NOT NULL AND drSumFlag = 1;
I have this query:
select *
from transaction_batch
where id IN
(
select MAX(id) as id
from transaction_batch
where status_id IN (1,2)
group by status_id
);
The inner query runs very fast (less than 0.1 seconds) to get two ID's, one for status 1, one for status 2, then it selects based on primary key so it is indexed. The explain query says that it's searching 135k rows using where only, and I cannot for the life of me figure out why this is so slow.
The inner query is run seperatly for every row of your table over and over again.
As there is no reference to the outer query in the inner query, I suggest you split those two queries and just insert the results of the inner query in the WHERE clause.
select b.*
from transaction_batch b
inner join (
select max(id) as id
from transaction_batch
where status_id in (1, 2)
group by status_id
) bm on b.id = bm.id
my first post here.. sorry about the lack of formatting
I had a performance problem shown below:
90sec: WHERE [Column] LIKE (Select [Value] From [Table]) //Dynamic, slow
1sec: WHERE [Column] LIKE ('A','B','C') //Hardcoded, fast
1sec: WHERE #CSV like CONCAT('%',[Column],'%') //Solution, below
I had tried joining rather than subquerying.
I had also tried a hardcoded CTE.
I had lastly tried a temp table.
None of these standard options worked, and I was not willing to dosp_execute option.
The only solution that worked as:
DECLARE #CSV nvarchar(max) = Select STRING_AGG([Value],',') From [Table];
// This yields #CSV = 'A,B,C'
...
WHERE #CSV LIKE CONCAT('%',[Column],'%')
I have 2 tables: tbl_taxclasses, tbl_taxclasses_regions
This is a one to many relationship, where the main record ID is classid.
I have a column inside the first table called regionscount
So, I create a Tax Class, in table 1. Then I add regions/states in table 2, assigning the classid to each region.
I perform a SELECT statement to count the regions with that same classid, and then I perform an UPDATE statement on tbl_taxclasses with that number. I update the regionscount column.
This means I'm writing 2 queries. Which is fine, but I was wondering if there was a way to do a SELECT statement inside the UPDATE statement, like this:
UPDATE `tbl_taxclasses` SET `regionscount` = [SELECT COUNT(regionsid) FROM `tbl_taxclasses_regions` WHERE classid = 1] WHERE classid = 1
I'm reaching here, since I'm not sure how robust MySQL is, but I do have the latest version, as of today. (5.5.15)
You could use a non-correlated subquery to do the work for you:
UPDATE
tbl_taxclasses c
INNER JOIN (
SELECT
COUNT(regionsid) AS n
FROM
tbl_taxclasses_regions
GROUP BY
classid
) r USING(classid)
SET
c.regionscount = r.n
WHERE
c.classid = 1
Turns out I was actually guessing right.
This works:
UPDATE `tbl_taxclasses`
SET `regionscount` = (
SELECT COUNT(regionsid) AS `num`
FROM `tbl_taxclasses_regions`
WHERE classid = 1)
WHERE classid = 1 LIMIT 1
I just needed to replace my brackets [] with parenthesis ().
I have a table like this (MySQL 5.0.x, MyISAM):
response{id, title, status, ...} (status: 1 new, 3 multi)
I would like to update the status from new (status=1) to multi (status=3) of all the responses if at least 20 have the same title.
I have this one, but it does not work :
UPDATE response SET status = 3 WHERE status = 1 AND title IN (
SELECT title FROM (
SELECT DISTINCT(r.title) FROM response r WHERE EXISTS (
SELECT 1 FROM response spam WHERE spam.title = r.title LIMIT 20, 1)
)
as u)
Please note:
I do the nested select to avoid the famous You can't specify target table 'response' for update in FROM clause
I cannot use GROUP BY for performance reasons. The query cost with a solution using LIMIT is way better (but it is less readable).
EDIT:
It is possible to do SELECT FROM an UPDATE target in MySQL. See solution here
The issue is on the data selected which is totaly wrong.
The only solution I found which works is with a GROUP BY:
UPDATE response SET status = 3
WHERE status = 1 AND title IN (SELECT title
FROM (SELECT title
FROM response
GROUP BY title
HAVING COUNT(1) >= 20)
as derived_response)
Thanks for your help! :)
MySQL doesn't like it when you try to UPDATE and SELECT from the same table in one query. It has to do with locking priorities, etc.
Here's how I would solve this problem:
SELECT CONCAT('UPDATE response SET status = 3 ',
'WHERE status = 1 AND title = ', QUOTE(title), ';') AS sql
FROM response
GROUP BY title
HAVING COUNT(*) >= 20;
This query produces a series of UPDATE statements, with the quoted titles that deserve to be updated embedded. Capture the result and run it as an SQL script.
I understand that GROUP BY in MySQL often incurs a temporary table, and this can be costly. But is that a deal-breaker? How frequently do you need to run this query? Besides, any other solutions are likely to require a temporary table too.
I can think of one way to solve this problem without using GROUP BY:
CREATE TEMPORARY TABLE titlecount (c INTEGER, title VARCHAR(100) PRIMARY KEY);
INSERT INTO titlecount (c, title)
SELECT 1, title FROM response
ON DUPLICATE KEY UPDATE c = c+1;
UPDATE response JOIN titlecount USING (title)
SET response.status = 3
WHERE response.status = 1 AND titlecount.c >= 20;
But this also uses a temporary table, which is why you try to avoid using GROUP BY in the first place.
I would write something straightforward like below
UPDATE `response`, (
SELECT title, count(title) as count from `response`
WHERE status = 1
GROUP BY title
) AS tmp
SET response.status = 3
WHERE status = 1 AND response.title = tmp.title AND count >= 20;
Is using GROUP BY really that slow ? The solution you tried to implement looks like requesting again and again on the same table and should be way slower than using GROUP BY if it worked.
This is a funny peculiarity with MySQL - I can't think of a way to do it in a single statement (GROUP BY or no GROUP BY).
You could select the appropriate response rows into a temporary table first then do the update by selecting from that temp table.
you'll have to use a temporary table:
create temporary table r_update (title varchar(10));
insert r_update
select title
from response
group
by title
having count(*) < 20;
update response r
left outer
join r_update ru
on ru.title = r.title
set status = case when ru.title is null then 3 else 1;