This question already has answers here:
MySQL DISTINCT on a GROUP_CONCAT()
(6 answers)
Closed 6 years ago.
I have a question about how to merge multiple row output into one row without having the same entry multiple times.
The basic setup is 4 tables:
room
appointments
users
actions
And 2 intermediate tables:
actions_appointments
users_appointments
I post the exact structure of the tables at the end of my post.
Multiple appointments can be made for one entry in the room table (n:1), but one or more users can join appointments (n:n) and one or more actions can be performed (n:n).
The problem is that I don't know how to output a single appointment with each user and action only being displayed ONCE per appointment.
With the example tables at the bottom of this post I basically want this to be my output:
|----------------|-----------|---------------------|-------------|------------------------|
| appointment_id | room_name | datetime | actions | userfullnames |
|----------------|-----------|---------------------|-------------|------------------------|
| 1 | Studio | 2016-09-01 15:30:00 | work, sleep | John Doe, Martin Smith |
| 2 | Office | 2017-04-02 13:00:00 | sleep | John Doe |
|----------------|-----------|---------------------|-------------|------------------------|
But with the queue I came up with I get this:
|----------------|-----------|---------------------|-------------|------------------------|
| appointment_id | room_name | datetime | actions | userfullnames |
|----------------|-----------|---------------------|-------------|------------------------|
| 1 | Studio | 2016-09-01 15:30:00 | work, sleep,| John Doe, Martin Smith,|
| | | | work, sleep | John Doe, Martin Smith |
| 2 | Office | 2017-04-02 13:00:00 | sleep | John Doe |
|----------------|-----------|---------------------|-------------|------------------------|
I mean I kinda get that I screwed up my joins but I'm totally stuck at the moment. Any hints? I feel like the solution is simple but I'm totally blind at the moment.
My queue:
SELECT
appointments.id AS 'appointment_id',
room.name AS 'room_name',
appointments.datetime,
GROUP_CONCAT(actions.name SEPARATOR ', ') AS 'actions',
GROUP_CONCAT(users.givenname, ' ', users.surname SEPARATOR ', ') AS 'userfullnames'
FROM appointments
INNER JOIN actions_appointments
ON appointments.id = actions_appointments.appointments_id
INNER JOIN actions
ON actions_appointments.actions_id = actions.id
INNER JOIN users_appointments
ON users_appointments.appointments_id = appointments.id
INNER JOIN users
ON users_appointments.users_id = users.id
INNER JOIN room
ON appointments.room_id = room.id
GROUP BY
appointments.id;
Table structure:
The basic tables:
|-------------------|
| room |
|-------------------|
| id | name |
|--------|----------|
| 1 | Office |
| 2 | Studio |
|-------------------|
|----------------------------------------|
| appointments |
|--------|---------|---------------------|
| id | room_id | datetime |
|--------|---------|---------------------|
| 1 | 2 | 2016-09-01 15:30:00 |
| 2 | 1 | 2017-04-02 13:00:00 |
|--------|---------|---------------------|
|-----------------------------------------|
| users |
|-----------------------------------------|
| id | username | givenname | surname |
|--------|----------|-----------|---------|
| 1 | j.doe | John | Doe |
| 2 | m.smith | Martin | Smith |
|--------|----------|-----------|---------|
|--------------------|
| actions |
|--------------------|
| id | name |
|--------|-----------|
| 1 | work |
| 2 | sleep |
|--------------------|
The intermediate tables:
|------------------------------|
| actions_appointments |
|------------------------------|
| actions_id | appointments_id |
|------------|-----------------|
| 1 | 1 |
| 2 | 1 |
| 2 | 2 |
|------------|-----------------|
|----------------------------|
| users_appointments |
|----------------------------|
| users_id | appointments_id |
|----------|-----------------|
| 1 | 1 |
| 2 | 1 |
| 1 | 2 |
|----------|-----------------|
Edit: The correct queue with DISTINCT
Thanks to Juan.Queiroz and Mike!
SELECT
appointments.id AS 'appointment_id',
room.name AS 'room_name',
appointments.datetime,
GROUP_CONCAT(DISTINCT actions.name SEPARATOR ', ') AS 'actions',
GROUP_CONCAT(DISTINCT users.givenname, ' ', users.surname SEPARATOR ', ') AS 'userfullnames'
FROM appointments
INNER JOIN actions_appointments
ON appointments.id = actions_appointments.appointments_id
INNER JOIN actions
ON actions_appointments.actions_id = actions.id
INNER JOIN users_appointments
ON users_appointments.appointments_id = appointments.id
INNER JOIN users
ON users_appointments.users_id = users.id
INNER JOIN room
ON appointments.room_id = room.id
GROUP BY
appointments.id;
GROUP BY
appointments.id,
room.name,
appointments.datetime
Related
I am using mysql and here is the schema that I have.
First Table: Domains
+-----------+--------------------+---------------+
| domain_id | domain_name | campaign_name |
+-----------+--------------------+---------------+
| 1 | test.org | campaign 1 |
| 2 | example.org | campaign 2 |
+-----------+--------------------+---------------+
Second Table: Users
+---------+-----------------+---------------+
| user_id | first_ame | last_name |
+---------+-----------------+---------------+
| 1 | John | Zimmer |
| 2 | Brian | Roberts |
| 3 | Jon | McNeill |
| 4 | Chris | Lambert |
| 5 | Vipul | Patel |
| 6 | Logan | Green |
+---------+-----------------+---------------+
Third Table: Emails
+----------+----------------------------------+-----------+---------+
| email_id | email | domain_id | user_id |
+----------+----------------------------------+-----------+---------+
| 1 | b1#test.org | 1 | 2 |
| 2 | b2#test.org | 1 | 1 |
| 3 | a1#example.org | 2 | 2 |
| 4 | a2#example.org | 2 | 3 |
| 5 | a3#example.org | 2 | 3 |
| 6 | a4#example.org | 2 | 4 |
+----------+----------------------------------+-----------+---------+
I want to get first_name, last_name and email of specific campaign i-e campaign 2 as shown follow.
Here is Online DB Query Editor
Kindly guide me how can I write SQL query to accomplish that. Thanks
If I am not missing anything, this is basically a join. You have the ids nicely matched between the tables, so you can do:
SELECT u.*, e.email, d.campaign_name
FROM Users u JOIN
Emails e
ON u.user_id = e.user_id JOIN
Domains d
ON e.domain_id = d.domain_id
WHERE d.campaign_name = 'campaign 2';
The email table is a so called bridge table between the other two. You have to perform a join between the three tables:
SELECT first_name, last_name, email
FROM Domains JOIN Emails ON Domains.domain_id = Emails.domain_id JOIN Users ON Emails.user_id = Users.user_id
WHERE Domains.campaign_name = ...
SELECT first_name as 'First Name',last_name as 'Last Name', email as 'email ID',campaign_name as 'Compaign Name'
FROM Users u
inner join Emails e
on e.user_id = u.user_id
inner join Domains d
on d.domain_id = e.domain_id
I have 3 tables like this:
table_events
+------+----------+----------------------+
| ID | Title | Employees |
+------+----------+----------------------+
| 1 | Event1 | john,james |
+------+----------+----------------------+
| 2 | Event2 | sarah,jessica |
+------+----------+----------------------+
table_check_in
+------+----------+----------+---------------------+
| ID | Time | EventID | By |
+------+----------+----------+---------------------+
| 1 | 08:30 | 1 | john |
+------+----------+----------+---------------------+
| 2 | 08:30 | 1 | james |
+------+----------+----------+---------------------+
| 3 | 09:30 | 1 | john |
+------+----------+----------+---------------------+
| 4 | 10:30 | 2 | sarah |
+------+----------+----------+---------------------+
| 5 | 10:35 | 2 | sarah |
+------+----------+----------+---------------------+
table_problems
+------+----------------+----------+---------------------+
| ID | Comment | EventID | By |
+------+----------------+----------+---------------------+
| 1 | Broken door | 1 | john |
+------+----------------+----------+---------------------+
| 2 | Slippery floor | 1 | john |
+------+----------------+----------+---------------------+
| 3 | Leaking tap | 1 | john |
+------+----------------+----------+---------------------+
| 4 | Broken window | 2 | jessica |
+------+----------------+----------+---------------------+
| 5 | Broken glass | 2 | jessica |
+------+----------------+----------+---------------------+
I would like to print something like this:
+------+----------+---------------+-------------------+-------------------+
| ID | Title | Employees | Count_Check_In | Count_Problems |
+------+----------+---------------+-------------------+-------------------+
| 1 | Event1 | john,james | john:2,james:1 | john:3,james:0 |
+------+----------+---------------+-------------------+-------------------+
| 2 | Event2 | sarah,jessica | sarah:2,jessica:0 | sarah:0,jessica:2 |
+------+----------+---------------+-------------------+-------------------+
I know this problem would be trivial if the database was designed properly, but we don't have the luxury of an application rewrite at the moment.
You need to initially get all the employees for each event id from check in and problem tables by using a union.
Then left join the counts from each of check in and problems table to the previous result to get the 0 counts as well.
Finally use a group_concat to get the result in one row for each event id.
select te.id,te.title,te.employees
,group_concat(concat(t.`By`,':',coalesce(tccnt.cnt,0))) count_check_in
,group_concat(concat(t.`By`,':',coalesce(tpcnt.cnt,0))) count_problems
from table_events te
left join (select eventid,`By` from table_check_in
union
select eventid,`By`from table_problems) t on te.id = t.eventid
left join (select eventid,`By`,count(*) cnt from table_check_in group by eventid,`By`) tccnt on tccnt.eventid = t.eventid and tccnt.`By`=t.`By`
left join (select eventid,`By`,count(*) cnt from table_problems group by eventid,`By`) tpcnt on tpcnt.eventid = t.eventid and tpcnt.`By`=t.`By`
group by te.id,te.title,te.employees
Sample Demo (thanks to #valex for setting up the schema)
You can use GROUP_CONCAT to get a result. Here is an example. The only thing missed is employees with 0 check ins or problems.
SELECT ID, Title,Employees,
GROUP_CONCAT(DISTINCT CONCAT(check_in.`By`,':',check_in.cnt))
as Count_Check_In,
GROUP_CONCAT(DISTINCT CONCAT(problems.`By`,':',problems.cnt))
as Count_Problems
FROM table_events
LEFT JOIN (SELECT EventID,`By`, COUNT(*) as cnt
FROM table_check_in
GROUP BY EventID,`By`) as check_in
ON table_events.ID = check_in.EventID
LEFT JOIN (SELECT EventID,`By`, COUNT(*) as cnt
FROM table_problems
GROUP BY EventID,`By`) as problems
ON table_events.ID = problems.EventID
GROUP BY table_events.id
Demo
I have 3 tables to join and need some help to make it work, this is my schema:
donations:
+--------------------+------------+
| uid | amount | date |
+---------+----------+------------+
| 1 | 20 | 2013-10-10 |
| 2 | 5 | 2013-10-03 |
| 2 | 50 | 2013-09-25 |
| 2 | 5 | 2013-10-01 |
+---------+----------+------------+
users:
+----+------------+
| id | username |
+----+------------+
| 1 | rob |
| 2 | mike |
+----+------------+
causes:
+--------------------+------------+
| id | uid | cause | <missing cid (cause id)
+---------+----------+------------+
| 1 | 1 | stop war |
| 2 | 2 | love |
| 3 | 2 | hate |
| 4 | 2 | love |
+---------+----------+------------+
Result I want (data cropped for reading purposes)
+---------+-------------+---------+-------------+
| id | username | amount | cause |
+---------+-------------+---------+-------------+
| 1 | rob | 20 | stop war |
| 2 | mike | 5 | love |
+---------+-------------+-----------------------+
etc...
This is my current query, but returns double data:
SELECT i.*, t.cause as tag_name
FROM users i
INNER JOIN donations tti ON (tti.uid = i.id)
INNER JOIN causes t ON (t.uid = tti.uid)
EDIT: fixed sql schema on fiddle
http://sqlfiddle.com/#!2/0e06c/1 schema and data
How I can do this?
It seems your table's model is not right. There should be a relation between the Causes and Donations.
If not when you do your joins you will get duplicated rows.
For instance. Your model could look like this:
Donations
+--------------------+------------+
| uid | amount | date | causeId
+---------+----------+------------+
| 1 | 20 | 2013-10-10 | 1
| 2 | 5 | 2013-10-03 | 2
| 2 | 50 | 2013-09-25 | 3
| 2 | 5 | 2013-10-01 | 2
+---------+----------+------------+
causes:
+----------------------+
| id | cause |
+---------+------------+
| 1 | stop war |
| 2 | love |
| 3 | hate |
+---------+------------+
And the right query then should be this
SELECT i.*, t.cause as tag_name
FROM users i
INNER JOIN donations tti ON (tti.uid = i.id)
INNER JOIN causes t ON (t.id = tti.causeId)
Try this
SELECT CONCAT(i.username ,' ',i.first_name) `name`,
SUM(tti.amount),
t.cause AS tag_name
FROM users i
LEFT JOIN donations tti ON (tti.uid = i.id)
INNER JOIN causes t ON (t.uid = tti.uid)
GROUP BY i.id
Fiddle
You need to match the id from both the users and causes table at the same time, like so:
SELECT i.*, t.cause as tag_name
FROM users i
INNER JOIN donations tti ON (tti.uid = i.id)
INNER JOIN causes t ON (t.uid = tti.uid and t.id = i.id)
Apologies for formatting, I'm typing this on a phone.
I need to get emtpy fields where data is repeated
For example an customer can have two or more contact persons, so query return (just shorted qyery resul):
CUSTOMER_NAME| CONTACT_PERSON|ETC..
dell | Ighor |etc..
dell | Dima |etc..
but I'm need :
CUSTOMER_NAME| CONTACT_PERSON|etc...
dell | Ighor |etc..
NULL | Dima |etc..
SELECT
`contact`.*,
`branch_has_equipment`.*,
`branch_has_contact`.*,
`equipment`.*,
`customer_has_branch`.*,
`branch`.*,
`customer`.*,
`ip`.*
FROM `customer`
INNER JOIN `customer_has_branch`
ON `customer`.`customer_id` = `customer_has_branch`.`customer_id`
INNER JOIN `branch`
ON `customer_has_branch`.`branch_id` = `branch`.`branch_id`
INNER JOIN `branch_has_equipment`
ON `branch`.`branch_id` = `branch_has_equipment`.`branch_id`
INNER JOIN `equipment`
ON `branch_has_equipment`.`equipment_id` = `equipment`.`equipment_id`
INNER JOIN `branch_has_contact`
ON `branch`.`branch_id` = `branch_has_contact`.`branch_id`
INNER JOIN `contact`
ON `branch_has_contact`.`contact_id` = `contact`.`contact_id`
INNER JOIN `equipment_has_ip`
ON `equipment`.`equipment_id` = `equipment_has_ip`.`equipment_id`
INNER JOIN `ip`
ON `equipment_has_ip`.`equipment_id` = `ip`.`ip_id`
WHERE `customer`.`inservice` = 'Yes'
ORDER BY `customer`.`customer_name`
in additional, tables ^
Customer
customer_id
customer_name
inservice
service_type
comment
Branch
branch_id
city
address
Equipment
equipment_id
brand
model
connection_param
connection_type
serial_number
id
release
Contact
contact_id
name
surname
phone_mobile
phone_work
phone_other
position
customer_has_branch_id
customer_id
branch_id
Since I have no idea how any of those tables relate to one another, my only answer to you is to use an OUTER JOIN, which will keep NULL results.
I'm not seriously advocating this solution because really i think this sort of thing should be handled in application level code (e.g. a bit of PHP), but anyway, consider the following:
SELECT * FROM my_table;
+------+--------+--------+
| game | points | player |
+------+--------+--------+
| 1 | 5 | Adam |
| 1 | 8 | Alan |
| 1 | 7 | Brian |
| 1 | 6 | John |
| 2 | 2 | Adam |
| 2 | 3 | Alan |
| 2 | 4 | Brian |
| 2 | 6 | John |
+------+--------+--------+
SELECT IF(game= #prev,'',game)
, #prev := game
FROM my_table ORDER BY game,player;
+-------------------------+---------------+
| IF(game= #prev,'',game) | #prev := game |
+-------------------------+---------------+
| 1 | 1 |
| | 1 |
| | 1 |
| | 1 |
| 2 | 2 |
| | 2 |
| | 2 |
| | 2 |
+-------------------------+---------------+
I have a db in mysql with multiple tables and would like to join multiple tables into one view to save me from having to build 3 or 4 sql statements or even one large joining statement in php to get the same info.
Here are all my tables that I want to join
track_title
+----+------------------+
| ID | TITLE |
+----+------------------+
| 1 | Title Here |
| 2 | Another Title |
| 3 | Some Other Title |
+----+------------------+
track_artist
+----+----------------+-----------+-----------+
| ID | TRACK_TITLE_ID | ARTIST_ID | SYMBOL_ID |
+----+----------------+-----------+-----------+
| 1 | 1 | 1 | 2 |
| 2 | 1 | 2 | 1 |
| 3 | 3 | 1 | 1 |
+----+----------------+-----------+-----------+
artist
+----+-------------+
| ID | ARTIST |
+----+-------------+
| 1 | Linkin Park |
| 2 | Metallica |
+----+-------------+
symbol
+----+--------+
| ID | SYMBOL |
+----+--------+
| 1 | |
| 2 | Feat. |
+----+--------+
tracklisting
+----+----------+----------+---------------+---------+
| ID | TRACK NO | TITLE_ID | VERSION | DISC NO |
+----+----------+----------+---------------+---------+
| 1 | 1 | 1 | | 1 |
| 2 | 1 | 2 | Album Version | 1 |
| 3 | 1 | 3 | Live Version | 1 |
+----+----------+----------+---------------+---------+
This is the final view I'm looking for
+----+----------+------------------+---------------+-----------------------------+---------+
| ID | TRACK NO | TITLE | VERSION | ARTIST | DISC NO |
+----+----------+------------------+---------------+-----------------------------+---------+
| 1 | 1 | Title Here | | Linkin Park Feat. Metallica | 1 |
| 2 | 1 | Another Title | Album Version | | 1 |
| 3 | 1 | Some Other Title | Live Version | Linkin Park | 1 |
+----+----------+------------------+---------------+-----------------------------+---------+
I have been bashing my head for the past 3 days with left, right, join and full join and just can't seem to get this to work.
Basically what I want to happen is the track_artist table will get the artist and symbol form the respective tables and concat them together into one column. Then join title and the concat column to have this view.
full_artist_view
+----------+------------------+-----------------------------+
| TITLE_ID | TITLE | FULL_ARTIST |
+----------+------------------+-----------------------------+
| 1 | Title Here | Linkin Park Feat. Metallica |
| 2 | Another Title | |
| 3 | Some Other Title | Linkin Park |
+----------+------------------+-----------------------------+
I have gotten this far but when I try join this to the tracklisting table I seem to crash my server which is getting very painful. No mysql error so I'm guessing I'm using the wrong join or this is just not possible.(though I can't see how this is not possible)
The tracklisting table is continuesly growing every week by 1000 records comfortable and is sitting at +- 75000 records.
To me this is the sql that should work, but doesn't
FROM full_artist_view LEFT JOIN tracklisting ON
full_artist_view.TITLE_ID = tracklisting.TITLE_ID
While I have only your small data sample and I can't see what your full_artist_view code looks like. You should be able to get the result using the following:
select tt.id,
tl.`track no`,
tt.title,
coalesce(tl.version, '') version,
group_concat(concat(coalesce(a.artist, ''), ' ', coalesce(s.symbol, '')) order by a.artist SEPARATOR ' ') artist,
tl.`disc no`
from track_title tt
inner join tracklisting tl
on tt.id = tl.TITLE_ID
left join track_artist ta
on tt.id = ta.TRACK_TITLE_ID
left join artist a
on ta.artist_id = a.id
left join symbol s
on ta.symbol_id = s.id
group by tt.id, tl.`track no`, tt.title, tl.version, tl.`disc no`
See SQL Fiddle with Demo. This returns:
| ID | TRACK NO | TITLE | VERSION | ARTIST | DISC NO |
---------------------------------------------------------------------------------------------
| 1 | 1 | Title Here | | Linkin Park Feat. Metallica | 1 |
| 2 | 1 | Another Title | Album Version | | 1 |
| 3 | 1 | Some Other Title | Live Version | Linkin Park | 1 |
Quick play, and I think (but not certain) it is something like this that you need:-
SELECT a.Id, a.Track_No, b.Title, a.Version, GROUP_CONCAT(CONCAT(d.Artists, e.Symbol)), a.Disc_No
FROM tracklisting a
INNER JOIN track_title b ON a.Title_id = b.Id
LEFT OUTER JOIN track_artist c ON b.Id = c.Track_Title_Id
LEFT OUTER JOIN artist d ON c.Artist_Id = d.Id
LEFT OUTER JOIN symbol e ON d.SymbolId = e.Id
GROUP BY a.Id, a.Track_No, b.Title, a.Version, a.Disc_No
But I might have missed something so let me know!