Dear All,

I am new to MySQL. Can i retrive the result of a query as the combination of different fields of a single record..

For example..
if the result record of a query is ... id(1), country(India), Location1(maharashtra), Location2(pune), Location3(Navi Mumbai)...

My doubt is that can i retrive the 3 locations as one field..

Please excuse me if this is a foolish question..

Regards,

Jino..

Dani AI

Generated

Short answer: yes. There are two common ways to return several location fields as a single column depending on how your data is stored.

If the three locations are columns in the same row, use MySQL string functions to concatenate them into one result. CONCAT_WS is convenient because it skips NULL values (so you don’t get a NULL result if one column is empty):

SELECT id,
       CONCAT_WS(', ', Location1, Location2, Location3) AS locations
FROM your_table;

If locations are stored as separate rows (the normalized approach that suggested), aggregate them with GROUP_CONCAT after joining the child table:

SELECT c.id, c.country,
       GROUP_CONCAT(l.name ORDER BY l.name SEPARATOR ', ') AS locations
FROM countries c
JOIN locations l ON l.country_id = c.id
GROUP BY c.id;

Notes and tips:

  • GROUP_CONCAT can truncate long lists; raise group_concat_max_len for large outputs (session or global) if needed.
  • CONCAT returns NULL if any argument is NULL; CONCAT_WS avoids that. Use IFNULL/COALESCE when you need to substitute defaults.
  • Prefer normalizing (one location per row) rather than columns Location1..N when the number of locations is variable. That makes indexing, searching and maintenance far easier.
  • For searching by partial city names, a plain LIKE '%term%' works but has performance limits; consider fulltext indexes (InnoDB supports them) or a dedicated search engine for large datasets.

Also: ’s & suggestion is from other SQL dialects — in MySQL use CONCAT/CONCAT_WS. For : either approach will give a single “locations” field; choose concatenation for fixed columns, aggregation for related rows.

Recommended Answers

All 2 Replies

If I understand correctly you want people to search for "muharashtra" or "pune" and get "india" as the result?

What I would do is setup 2 mysql tables in the one database.

1 called "countries"
1 called "cities"

like so:

countries
country_id
country_name

cities
city_id
country_id
city_name

You can now do something along the lines of:

$sql = "SELECT countries.name FROM countries,cities WHERE countries.country_id=cities.country_id AND cities.city_name LIKE '%$SEARCH_STRING%'";

Comprende?

you can try something like this:
SELECT Column1 & ' ' & Column2 AS Name FROM ....

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.