简体   繁体   中英

Writing a correlated sub-query in my select query

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM