SQL - group by another SQL statement with multiple rows2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Add a column with a default value to an existing table in SQL ServerHow to concatenate text from multiple rows into a single text string in SQL server?Can I concatenate multiple MySQL rows into one field?Inserting multiple rows in a single SQL query?How do I UPDATE from a SELECT in SQL Server?Select first row in each GROUP BY group?SQL select only rows with max value on a columnHow to import an SQL file using the command line in MySQL?How to convert a row value to column header in mysql for Wordpress database

Meaning of "SEVERA INDEOVI VAS" from 3rd Century slab

Good allowance savings plan?

Instead of Universal Basic Income, why not Universal Basic NEEDS?

Welcoming 2019 Pi day: How to draw the letter π?

Does the statement `int val = (++i > ++j) ? ++i : ++j;` invoke undefined behavior?

Informing my boss about remarks from a nasty colleague

Possible Leak In Concrete

Can anyone tell me why this program fails?

How to answer questions about my characters?

What are the possible solutions of the given equation?

Counting certain elements in lists

What is IP squat space

How to write cleanly even if my character uses expletive language?

Calculus II Professor will not accept my correct integral evaluation that uses a different method, should I bring this up further?

Do I need life insurance if I can cover my own funeral costs?

Russian cases: A few examples, I'm really confused

Identifying the interval from A♭ to D♯

Can the damage from a Talisman of Pure Good (or Ultimate Evil) be non-lethal?

RegionDifference for Cylinder and Cuboid

Old race car problem/puzzle

Why does Deadpool say "You're welcome, Canada," after shooting Ryan Reynolds in the end credits?

Why did it take so long to abandon sail after steamships were demonstrated?

Life insurance that covers only simultaneous/dual deaths

How do anti-virus programs start at Windows boot?



SQL - group by another SQL statement with multiple rows



2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Add a column with a default value to an existing table in SQL ServerHow to concatenate text from multiple rows into a single text string in SQL server?Can I concatenate multiple MySQL rows into one field?Inserting multiple rows in a single SQL query?How do I UPDATE from a SELECT in SQL Server?Select first row in each GROUP BY group?SQL select only rows with max value on a columnHow to import an SQL file using the command line in MySQL?How to convert a row value to column header in mysql for Wordpress database










1















I am trying to get an SQL statement for wordpress to work by grouping different meta columns.



I have one table with votes, one table with locations and one table with reference links to some cities (Each city can contain multiple locations).



I am trying to group all votes based on each big city, but I am having some trouble putting the two SQL statements into one.



Here is the query to get the top 50 locations in terms of number of votes:



SELECT Count(*) as Amount, meta.meta_value as Location FROM wp_votes as votes
LEFT JOIN wp_postmeta as meta ON votes.`post_id` = meta.`post_id`
WHERE meta.meta_key = 'location'
AND votes.`post_id` IS NOT NULL AND votes.`post_id` <> 0
GROUP BY meta.meta_value
ORDER BY Amount DESC
LIMIT 50;


This returns a response like this:



|---------------------|------------------|
| Amount | meta_value |
|---------------------|------------------|
| 1250 | Brooklyn |
|---------------------|------------------|
| 400 | Manhattan |
|---------------------|------------------|
| 300 | Chicago |


And here is the query to get the Cities based on the location. It returns a list of cities (in the example above it would just return New York) and the two locations "Brooklyn", "Manhattan" would be "included" in New York.



SELECT meta_value FROM wp_posts as location
LEFT JOIN wp_postmeta as city ON city.`post_id` = location.`ID`
WHERE city.`meta_key` = 'reference'
GROUP BY city.`meta_value`;


The idea here is to map these two queries together, so that if there is a match in location from the first query and the location in the second query, it would group the rows by the city name instead.



So the output for the combined queries would be:



|---------------------|------------------|
| Amount | meta_value |
|---------------------|------------------|
| 1650 | New York |
|---------------------|------------------|
| 300 | Chicago |
|---------------------|------------------|


Is this possible?










share|improve this question






















  • That LEFT JOIN returns regular INNER JOIN result since you have the outer table conditions in the WHERE clause. Move city conditions to the ON clause to get true LEFT JOIN result.

    – jarlh
    Mar 7 at 12:25
















1















I am trying to get an SQL statement for wordpress to work by grouping different meta columns.



I have one table with votes, one table with locations and one table with reference links to some cities (Each city can contain multiple locations).



I am trying to group all votes based on each big city, but I am having some trouble putting the two SQL statements into one.



Here is the query to get the top 50 locations in terms of number of votes:



SELECT Count(*) as Amount, meta.meta_value as Location FROM wp_votes as votes
LEFT JOIN wp_postmeta as meta ON votes.`post_id` = meta.`post_id`
WHERE meta.meta_key = 'location'
AND votes.`post_id` IS NOT NULL AND votes.`post_id` <> 0
GROUP BY meta.meta_value
ORDER BY Amount DESC
LIMIT 50;


This returns a response like this:



|---------------------|------------------|
| Amount | meta_value |
|---------------------|------------------|
| 1250 | Brooklyn |
|---------------------|------------------|
| 400 | Manhattan |
|---------------------|------------------|
| 300 | Chicago |


And here is the query to get the Cities based on the location. It returns a list of cities (in the example above it would just return New York) and the two locations "Brooklyn", "Manhattan" would be "included" in New York.



SELECT meta_value FROM wp_posts as location
LEFT JOIN wp_postmeta as city ON city.`post_id` = location.`ID`
WHERE city.`meta_key` = 'reference'
GROUP BY city.`meta_value`;


The idea here is to map these two queries together, so that if there is a match in location from the first query and the location in the second query, it would group the rows by the city name instead.



So the output for the combined queries would be:



|---------------------|------------------|
| Amount | meta_value |
|---------------------|------------------|
| 1650 | New York |
|---------------------|------------------|
| 300 | Chicago |
|---------------------|------------------|


Is this possible?










share|improve this question






















  • That LEFT JOIN returns regular INNER JOIN result since you have the outer table conditions in the WHERE clause. Move city conditions to the ON clause to get true LEFT JOIN result.

    – jarlh
    Mar 7 at 12:25














1












1








1








I am trying to get an SQL statement for wordpress to work by grouping different meta columns.



I have one table with votes, one table with locations and one table with reference links to some cities (Each city can contain multiple locations).



I am trying to group all votes based on each big city, but I am having some trouble putting the two SQL statements into one.



Here is the query to get the top 50 locations in terms of number of votes:



SELECT Count(*) as Amount, meta.meta_value as Location FROM wp_votes as votes
LEFT JOIN wp_postmeta as meta ON votes.`post_id` = meta.`post_id`
WHERE meta.meta_key = 'location'
AND votes.`post_id` IS NOT NULL AND votes.`post_id` <> 0
GROUP BY meta.meta_value
ORDER BY Amount DESC
LIMIT 50;


This returns a response like this:



|---------------------|------------------|
| Amount | meta_value |
|---------------------|------------------|
| 1250 | Brooklyn |
|---------------------|------------------|
| 400 | Manhattan |
|---------------------|------------------|
| 300 | Chicago |


And here is the query to get the Cities based on the location. It returns a list of cities (in the example above it would just return New York) and the two locations "Brooklyn", "Manhattan" would be "included" in New York.



SELECT meta_value FROM wp_posts as location
LEFT JOIN wp_postmeta as city ON city.`post_id` = location.`ID`
WHERE city.`meta_key` = 'reference'
GROUP BY city.`meta_value`;


The idea here is to map these two queries together, so that if there is a match in location from the first query and the location in the second query, it would group the rows by the city name instead.



So the output for the combined queries would be:



|---------------------|------------------|
| Amount | meta_value |
|---------------------|------------------|
| 1650 | New York |
|---------------------|------------------|
| 300 | Chicago |
|---------------------|------------------|


Is this possible?










share|improve this question














I am trying to get an SQL statement for wordpress to work by grouping different meta columns.



I have one table with votes, one table with locations and one table with reference links to some cities (Each city can contain multiple locations).



I am trying to group all votes based on each big city, but I am having some trouble putting the two SQL statements into one.



Here is the query to get the top 50 locations in terms of number of votes:



SELECT Count(*) as Amount, meta.meta_value as Location FROM wp_votes as votes
LEFT JOIN wp_postmeta as meta ON votes.`post_id` = meta.`post_id`
WHERE meta.meta_key = 'location'
AND votes.`post_id` IS NOT NULL AND votes.`post_id` <> 0
GROUP BY meta.meta_value
ORDER BY Amount DESC
LIMIT 50;


This returns a response like this:



|---------------------|------------------|
| Amount | meta_value |
|---------------------|------------------|
| 1250 | Brooklyn |
|---------------------|------------------|
| 400 | Manhattan |
|---------------------|------------------|
| 300 | Chicago |


And here is the query to get the Cities based on the location. It returns a list of cities (in the example above it would just return New York) and the two locations "Brooklyn", "Manhattan" would be "included" in New York.



SELECT meta_value FROM wp_posts as location
LEFT JOIN wp_postmeta as city ON city.`post_id` = location.`ID`
WHERE city.`meta_key` = 'reference'
GROUP BY city.`meta_value`;


The idea here is to map these two queries together, so that if there is a match in location from the first query and the location in the second query, it would group the rows by the city name instead.



So the output for the combined queries would be:



|---------------------|------------------|
| Amount | meta_value |
|---------------------|------------------|
| 1650 | New York |
|---------------------|------------------|
| 300 | Chicago |
|---------------------|------------------|


Is this possible?







mysql sql database wordpress






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 7 at 12:24









user2868900user2868900

8413




8413












  • That LEFT JOIN returns regular INNER JOIN result since you have the outer table conditions in the WHERE clause. Move city conditions to the ON clause to get true LEFT JOIN result.

    – jarlh
    Mar 7 at 12:25


















  • That LEFT JOIN returns regular INNER JOIN result since you have the outer table conditions in the WHERE clause. Move city conditions to the ON clause to get true LEFT JOIN result.

    – jarlh
    Mar 7 at 12:25

















That LEFT JOIN returns regular INNER JOIN result since you have the outer table conditions in the WHERE clause. Move city conditions to the ON clause to get true LEFT JOIN result.

– jarlh
Mar 7 at 12:25






That LEFT JOIN returns regular INNER JOIN result since you have the outer table conditions in the WHERE clause. Move city conditions to the ON clause to get true LEFT JOIN result.

– jarlh
Mar 7 at 12:25













1 Answer
1






active

oldest

votes


















0














Just include a second JOIN to get the reference:



SELECT c.meta_value as city, Count(*) as Amount 
FROM wp_votes v LEFT JOIN
wp_postmeta l
ON v.`post_id` = l.`post_id` AND
l.meta_key = 'location' LEFT JOIN
wp_postmeta c
ON l.id = c.`post_id` AND
c.meta_key = 'city'
WHERE v.`post_id` IS NOT NULL AND v.`post_id` <> 0
GROUP BY c.meta_value
ORDER BY Amount DESC
LIMIT 50;





share|improve this answer

























  • Thank you for the answer! Although, when running this query I just get one single row with all votes as result. The problem might be that the locations and cities in the second query are separate entries (i.e. not linked to the posts in the first query). So I need to check if the location-values in the first query matches any of the location-values in the second query and then do the sorting

    – user2868900
    Mar 7 at 12:48











  • @user2868900 . . . Something seems wrong with the data model, because you are using post_id for a different purpose. In any case, this is fixed by adjusting the JOIN condition.

    – Gordon Linoff
    Mar 7 at 13:34











  • The data model becomes really messed up due to this being a wordpress site, and the functionality added is based on Advanced Custom Fields and frontend functionality rather than an actual data model. Thank you, I will try to make it work.

    – user2868900
    Mar 7 at 14:03










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55043739%2fsql-group-by-another-sql-statement-with-multiple-rows%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














Just include a second JOIN to get the reference:



SELECT c.meta_value as city, Count(*) as Amount 
FROM wp_votes v LEFT JOIN
wp_postmeta l
ON v.`post_id` = l.`post_id` AND
l.meta_key = 'location' LEFT JOIN
wp_postmeta c
ON l.id = c.`post_id` AND
c.meta_key = 'city'
WHERE v.`post_id` IS NOT NULL AND v.`post_id` <> 0
GROUP BY c.meta_value
ORDER BY Amount DESC
LIMIT 50;





share|improve this answer

























  • Thank you for the answer! Although, when running this query I just get one single row with all votes as result. The problem might be that the locations and cities in the second query are separate entries (i.e. not linked to the posts in the first query). So I need to check if the location-values in the first query matches any of the location-values in the second query and then do the sorting

    – user2868900
    Mar 7 at 12:48











  • @user2868900 . . . Something seems wrong with the data model, because you are using post_id for a different purpose. In any case, this is fixed by adjusting the JOIN condition.

    – Gordon Linoff
    Mar 7 at 13:34











  • The data model becomes really messed up due to this being a wordpress site, and the functionality added is based on Advanced Custom Fields and frontend functionality rather than an actual data model. Thank you, I will try to make it work.

    – user2868900
    Mar 7 at 14:03















0














Just include a second JOIN to get the reference:



SELECT c.meta_value as city, Count(*) as Amount 
FROM wp_votes v LEFT JOIN
wp_postmeta l
ON v.`post_id` = l.`post_id` AND
l.meta_key = 'location' LEFT JOIN
wp_postmeta c
ON l.id = c.`post_id` AND
c.meta_key = 'city'
WHERE v.`post_id` IS NOT NULL AND v.`post_id` <> 0
GROUP BY c.meta_value
ORDER BY Amount DESC
LIMIT 50;





share|improve this answer

























  • Thank you for the answer! Although, when running this query I just get one single row with all votes as result. The problem might be that the locations and cities in the second query are separate entries (i.e. not linked to the posts in the first query). So I need to check if the location-values in the first query matches any of the location-values in the second query and then do the sorting

    – user2868900
    Mar 7 at 12:48











  • @user2868900 . . . Something seems wrong with the data model, because you are using post_id for a different purpose. In any case, this is fixed by adjusting the JOIN condition.

    – Gordon Linoff
    Mar 7 at 13:34











  • The data model becomes really messed up due to this being a wordpress site, and the functionality added is based on Advanced Custom Fields and frontend functionality rather than an actual data model. Thank you, I will try to make it work.

    – user2868900
    Mar 7 at 14:03













0












0








0







Just include a second JOIN to get the reference:



SELECT c.meta_value as city, Count(*) as Amount 
FROM wp_votes v LEFT JOIN
wp_postmeta l
ON v.`post_id` = l.`post_id` AND
l.meta_key = 'location' LEFT JOIN
wp_postmeta c
ON l.id = c.`post_id` AND
c.meta_key = 'city'
WHERE v.`post_id` IS NOT NULL AND v.`post_id` <> 0
GROUP BY c.meta_value
ORDER BY Amount DESC
LIMIT 50;





share|improve this answer















Just include a second JOIN to get the reference:



SELECT c.meta_value as city, Count(*) as Amount 
FROM wp_votes v LEFT JOIN
wp_postmeta l
ON v.`post_id` = l.`post_id` AND
l.meta_key = 'location' LEFT JOIN
wp_postmeta c
ON l.id = c.`post_id` AND
c.meta_key = 'city'
WHERE v.`post_id` IS NOT NULL AND v.`post_id` <> 0
GROUP BY c.meta_value
ORDER BY Amount DESC
LIMIT 50;






share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 7 at 13:34

























answered Mar 7 at 12:28









Gordon LinoffGordon Linoff

786k35310416




786k35310416












  • Thank you for the answer! Although, when running this query I just get one single row with all votes as result. The problem might be that the locations and cities in the second query are separate entries (i.e. not linked to the posts in the first query). So I need to check if the location-values in the first query matches any of the location-values in the second query and then do the sorting

    – user2868900
    Mar 7 at 12:48











  • @user2868900 . . . Something seems wrong with the data model, because you are using post_id for a different purpose. In any case, this is fixed by adjusting the JOIN condition.

    – Gordon Linoff
    Mar 7 at 13:34











  • The data model becomes really messed up due to this being a wordpress site, and the functionality added is based on Advanced Custom Fields and frontend functionality rather than an actual data model. Thank you, I will try to make it work.

    – user2868900
    Mar 7 at 14:03

















  • Thank you for the answer! Although, when running this query I just get one single row with all votes as result. The problem might be that the locations and cities in the second query are separate entries (i.e. not linked to the posts in the first query). So I need to check if the location-values in the first query matches any of the location-values in the second query and then do the sorting

    – user2868900
    Mar 7 at 12:48











  • @user2868900 . . . Something seems wrong with the data model, because you are using post_id for a different purpose. In any case, this is fixed by adjusting the JOIN condition.

    – Gordon Linoff
    Mar 7 at 13:34











  • The data model becomes really messed up due to this being a wordpress site, and the functionality added is based on Advanced Custom Fields and frontend functionality rather than an actual data model. Thank you, I will try to make it work.

    – user2868900
    Mar 7 at 14:03
















Thank you for the answer! Although, when running this query I just get one single row with all votes as result. The problem might be that the locations and cities in the second query are separate entries (i.e. not linked to the posts in the first query). So I need to check if the location-values in the first query matches any of the location-values in the second query and then do the sorting

– user2868900
Mar 7 at 12:48





Thank you for the answer! Although, when running this query I just get one single row with all votes as result. The problem might be that the locations and cities in the second query are separate entries (i.e. not linked to the posts in the first query). So I need to check if the location-values in the first query matches any of the location-values in the second query and then do the sorting

– user2868900
Mar 7 at 12:48













@user2868900 . . . Something seems wrong with the data model, because you are using post_id for a different purpose. In any case, this is fixed by adjusting the JOIN condition.

– Gordon Linoff
Mar 7 at 13:34





@user2868900 . . . Something seems wrong with the data model, because you are using post_id for a different purpose. In any case, this is fixed by adjusting the JOIN condition.

– Gordon Linoff
Mar 7 at 13:34













The data model becomes really messed up due to this being a wordpress site, and the functionality added is based on Advanced Custom Fields and frontend functionality rather than an actual data model. Thank you, I will try to make it work.

– user2868900
Mar 7 at 14:03





The data model becomes really messed up due to this being a wordpress site, and the functionality added is based on Advanced Custom Fields and frontend functionality rather than an actual data model. Thank you, I will try to make it work.

– user2868900
Mar 7 at 14:03



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55043739%2fsql-group-by-another-sql-statement-with-multiple-rows%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme