I need to build a MySQL query that returns only the common columns for a group of rows. I've a table named projects that has id_country, id_auto, id_prov and id_pobl. I select a group of projects by an area with this query:
SELECT DISTINCT codpais, codauto, codprov, codpobl
FROM projects
WHERE area=1
This returns me:
id_country | id_auto | id_prov | id_pobl
155 | 1 | 4 | 31
155 | 1 | 4 | 10
155 | 1 | 4 | 25
But from the query above I only want the results that are equal on each row: id_country, id_auto and id_prov. One option will be return id_pobl as NULL if is not same result. If id_auto, id_prov or id_pobl is not the same on each result I don't needed. If the id_country is different, I needed it anyway.
I explain this because my English is not good so you can understand me. In my website I need to print the common country / province / city... of a group of projects. For example, if 155=Spain, 1=Comunidad de Madrid, 4=Madrid and 31, 10 and 25 are cities of the province of Madrid I only need to show (in the website): Spain / Comunidad de Madrid / Madrid. If only id_country and id_auto are the same on each row, I will show: Spain / Comunidad de Madrid. If each id_country is different, I'll show the countries separated by comas, like: Spain, Portugal, France...
Well I'm saying the names but I need the ids and later I'll do the JOIN/LEFT JOIN
Update, example:
I have a group of 5 projects that every 开发者_如何学编程project has a id_country, id_auto, id_prov and id_pobl. When I have to show it in PHP, I've to show the common country, auto, prov and pobl.
If the country, auto, prov and pobl are the same in every project I'll need to show in the HTML rendered page with PHP:
Country / Auto / Prov / Pobl
If the country, auto and prov are the same in every project but pobl is different, I need to show:
Country / Auto / Prov
If the country and auto are the same but prov and pobl are different, I need to show:
Country / Auto
If the country are different in every project, I need to show the list of countries:
Country 1, Country 2, Country 3...
Wish that now is more clear!
Thank you in advance!
I think what you want is a grouped query. Something like:
SELECT codpais, codauto, codprov, GROUP_CONCAT(DISTINCT codpobl) AS pobl
FROM projects
WHERE area=1
GROUP BY codpais, codauto, codprov
精彩评论