Let's say we have a tally_sheets
table which contains some tally sheets information like in the following description and a persons
table described below with a tally_sheets
field containing a list of tally sheet's IDs separated by comma.
Every tally sheet contain only peoples from a country/city combination.
How to get a list of all tally sheets with all fields from tally_sheets
and country
and city
fields from persons
table?
mysql> desc tally_sheets;
+-----------+--------------+
| Field | Type |
+-----------+--------------+
| id | int(10) |
| date | char(10) |
| person | varchar(64) |
| comment | varchar(255) |
| timestamp | timestamp |
+-----------+--------------+
mysql> desc persons;
+------------------+--------------+
| Field | Type |
+------------------+--------------+
| id | int(11) |
| name | varchar(30) |
| country | varchar(60) |
| city | varchar(60) |
| tally_sheets | varchar(64) | <== comma separated tally_sheet's ID
+------------------+--------------+
Running
SELECT ts.id, ts.date, p.country, p.city, ts.person, ts.`comment`, '0' AS sqlExclude
FROM tally_sheets ts
RIGHT JOIN persons p ON ts.id IN (p.tally_sheets)
GROUP BY p.city
will give all country/city combinations but all the other fields are NULL
.
+------+------+------------+--------------------+--------+---------+------------+
| id | date | country | city | person | comment | sqlExclude |
+------+------+------------+--------------------+--------+---------+------------+
| NULL | NULL | Country1 | City1 | NULL | NULL | 0 |
| NULL | NULL | Country1 | City2 | NULL | NULL | 0 |
| NULL | NULL | Country2 | City3 | NULL | NULL | 0 |
+------+------+------------+--------------------+--------+---------+------------+
Running SELECT ts.id, p.country, p.city FROM persons p LEFT JOIN tally_sheets ts ON ts.id IN (p.tally_sheets) GROUP BY p.city
will also return NULL
fields.
+------+------------+--------------------+
| id | country | city |
+------+------------+--------------------+
| NULL | Country1 | City1 |
| NULL | Country1 | City2 |
| NULL | Country2 | City3 |
+------+------------+--------------------+
What i'm doing wrong? Thanks a lot!