Mysql query from two tables as parent and child objects - mysql

I am creating an Angularjs app with two tables "Contact Group" and "Contact List". The contact list table items have corespondent id to items in the contact group.
What I want to achieve is a MySQL/Sqlite select query that will have each contact list items as a child object of its parent.
contact_group
id | title
------------
1 | friends
2 | mates
3 | family
contact_list
id | gID | name | number
--------------------------
1 | 1 | dave |0208500
2 | 1 | dan |4213839
3 | 1 | sans |5656434
4 | 2 | fola |1918982
5 | 3 | brian|2398343
6 | 5 | grace|0934232
Select query results examples (this is what i want to get)
id: 1
title: friends
child: {id:1, name:dave, number:0208500}, {id:2, name:dan, number:4213839},{id:3, name:sans, number:5656434}
I case there is another way of doing it, this what i want to achieve. I have created an accordion with title from the contact_group title. Under each accordion are the correspondent contacts from the contact_list.
I will be glad if anyone can help me. Thank you

In order to achieve this you will have to use MySql GROUP_CONCAT (documentation here: https://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat)
Using GROUP_CONCAT we will be able to join all matching rows from the contacts TB into a string in one column. With some more formatting of the text we glue together from the contacts TB and additional usage of CONCAT we will build the string in this column as a JSON string that you will then be able to work with on your application.
Here is the SQL:
SELECT
a.id,
a.title,
CONCAT(
'[',
GROUP_CONCAT(
CONCAT(
'{"id":',
b.id,
', "name":"',
b. `name`,
'", "number":"',
b.number,
'"}'
)
ORDER BY
b.`name`
), ']')
AS people
FROM
contact_group AS a
LEFT JOIN contact_list AS b ON a.id = b.gID
GROUP BY
a.id,
a.title
And this is the result we will get:
Don't forget to add Indexes and Foreign keys to your tables so query processing would be better.
SQLLITE Version:
in order to adjust the query to sqllite, there are 2 features that need to be changed.
SqlLite uses || operator instead of CONCAT and it does not support ORDER BY inside the GROUP_CONCAT. so for the SQLLITE DB the query will look like this:
SELECT
a.id,
a.title,
'[' ||
GROUP_CONCAT(
'{"id":' ||
b.id ||
', "name":"' ||
b. `name` ||
'", "number":"' ||
b.number ||
'"}'
) || ']'
AS people
FROM
contact_group AS a
LEFT JOIN contact_list AS b ON a.id = b.gID
GROUP BY
a.id,
a.title
MySQL Fiddle Demo
SqlLite Fiddle Demo

Try the below query,
select * from contact_group join contact_list on contact_group.id= contact_list.gid

Related

Concatenate results from SQL query base on another column

SELECT DISTINCT * FROM ( SELECT hostname, table2.user-id, table2.user-team from
INNER JOIN table2 on table1.id = table2.id)
So at the moment my SQL query outputs this:
hostname user-id user-team
a 1 alpha
a 2 beta
b 3 beta
c 4 alpha
c 1 null
c 3 alpha
but what I want is something like this:
hostname user-id user-team
a 1, 2 alpha, beta
b 3 beta
c 4, 1, 3 alpha
I'm trying to use a GROUP BY hostname statement at the end of my query, and a GROUP_CONCAT(DISTINCT user_id SEPARATOR ', '), GROUP_CONCAT(DISTINCT user_team SEPARATOR ', '),
But this then only returns the first hostname result and all the values possible for the user-id and team-id. I feel like I'm close, but I can't quite get it. Any help?
(At present it returns)
hostname user-id user-team
a 1,2,3,4 alpha, beta
with this as the SQL query
SELECT DISTINCT *
FROM ( SELECT hostname,
GROUP_CONCAT(DISTINCT table2.user-id SEPARATOR(', '),
GROUP_CONCAT(DISTINCT table2.team-id SEPARATOR(', ')
from table1
INNER JOIN table2 on table1.id = table2.id)
GROUP BY hostname
Although the queries arean't 100% accurate, that is the logic in them (they just contain far more columns in the real world problem I have.)
I think you miss the GROUP BY
SQL DEMO
SELECT hostname,
GROUP_CONCAT(DISTINCT user_id SEPARATOR ', ') as users,
GROUP_CONCAT(DISTINCT user_team SEPARATOR ', ') as teams
FROM Table1
GROUP BY hostname
OUTPUT
| hostname | users | teams |
|----------|---------|-------------|
| a | 1, 2 | alpha, beta |
| b | 3 | beta |
| c | 4, 1, 3 | alpha |
EDIT: After you edit your question, the problem was you put the GROUP BY outside of the subquery

Use a GROUP_CONCAT and JOIN in a subquery

I have a DB under MySQL with one main table with unique id, few tables that list different choices (with one id column, one text column to describe the item). So, for one record in the main table, I can have multiple choices associated to the choice table.
I'd like to create a View where all information could be visible, using GROUP_CONCAT to concatenate into one field the different choices from a given 'choice' table. However, my query repeats many times each list of choices when the record is related to other multiple choices from another 'choice' table. The query returns all the possible combinations between those choices...
Here my query (reduced to 2 'choice' tables -t_age, t_animal- for the example)
SELECT general.id_g,
GROUP_CONCAT(CAST(t_age AS CHAR) SEPARATOR ', ') AS age,
GROUP_CONCAT(CAST(t_animal AS CHAR) SEPARATOR ', ') AS animal
FROM general
LEFT JOIN interm_age
INNER JOIN t_age ON interm_age.id_age = t_age.id_age
ON general.id_g = interm_age.id_g
LEFT JOIN interm_animal
INNER JOIN t_animal ON interm_animal.id_animal = t_animal.id_animal
ON general.id_g = interm_animal.id_g
GROUP BY id_g;
I tried to include each CONCAT/JOIN within a subquery into a main SELECT as followed, but MySQL tells me "returns more than 1row", which is the case indeed. And?
SELECT id_g, (
SELECT GROUP_CONCAT(CAST(t_age AS CHAR) SEPARATOR ', ')
FROM general
LEFT JOIN interm_age
INNER JOIN t_age ON interm_age.id_age = t_age.id_age
ON general.id_g = interm_age.id_g
GROUP BY general.id_g )
FROM general;
[EDIT]
In more details, this is my DB (with FK)
general
-----------
id_g | date
902 | 2016/01/01
956 | 2016/02/01
959 | 2016/02/01
interm_age
-----------
id_age | id_g
1 | 902
3 | 902
1 | 956
4 | 956
interm_animal
-----------
id_animal | id_g
1 | 902
5 | 902
5 | 959
7 | 959
t_age
-----------
id_age | age
1 | <10y
3 | >10y
4 | >60y
t_animal
-----------
id_animal | animal
1 | bird
5 | mammal
7 | insect
And I would like something like :
id_g | date | age | animal
902 | 2016/01/01 | <10y, >10y | bird, mammal
and so on...
Thanks in advance!
Although it would be better if you provided some sample data, actual results, and expected results, I'll have a stab at the solution.
The issue probably is that you have multiple matching records in the joined tables, which leads to duplication of values within group_concat().
As MySQL documentation on group_concat() indicates, you can use the distinct keyword to remove duplicate values:
To eliminate duplicate values, use the DISTINCT clause.
SELECT general.id_g,
GROUP_CONCAT(DISTINCT CAST(t_age AS CHAR) SEPARATOR ', ') AS age,
GROUP_CONCAT(DISTINCT CAST(t_animal AS CHAR) SEPARATOR ', ') AS animal
FROM general
LEFT JOIN interm_age
INNER JOIN t_age ON interm_age.id_age = t_age.id_age
ON general.id_g = interm_age.id_g
LEFT JOIN interm_animal
INNER JOIN t_animal ON interm_animal.id_animal = t_animal.id_animal
ON general.id_g = interm_animal.id_g
GROUP BY id_g;
Try this
SELECT general.id_g,
GROUP_CONCAT(CAST(t_age AS CHAR) SEPARATOR ', ') AS age,
GROUP_CONCAT(CAST(t_animal AS CHAR) SEPARATOR ', ') AS animal
FROM general
LEFT JOIN interm_age
INNER JOIN t_age ON interm_age.id_age = t_age.id_age AND general.id_g = interm_age.id_g
LEFT JOIN interm_animal
INNER JOIN t_animal ON interm_animal.id_animal = t_animal.id_animal AND general.id_g = interm_animal.id_g
GROUP BY id_g;
Hope this helps.

SQL - SELECT Merge rows if multiple results are found

I have an SQL table setup similar to this:
name | subject |
-------+----------+
Harry | Painting |
Sandra | Soccer |
Sandra | English |
How can I write a select statement that merges the rows if they have multiple subject, so it would output a result like this:
name | subject 1 | subject 2 |
-------+------------+------------+
Harry | Painting | |
Sandra | Soccer | English |
You shouldn't. The best approach is to join the tables so you have:
Harry, Painting
Sandra, Soccer
Sandra, English
And then process these rows in your scripting language (PHP etc) to turn it into the hierarchical data structure you desire
In your example above, what would happen when there's 3 subjects per person, 10, 100, etc.
SQL only really works with two dimensional data. For three dimensions you either need to pre/post process as i've suggested, or move to something like NoSQL mongoDB that deals with structured objects instead of table rows.
Since you mentioned that the maximum number of subjects is only 2, you can therefore, generate a sequential number for each name and used that to pivot the columns.
SELECT Name,
MAX(CASE WHEN rn = 1 THEN Subject END) Subject1,
MAX(CASE WHEN rn = 2 THEN Subject END) Subject2
FROM
(
SELECT A.name,
A.subject,
(
SELECT COUNT(*)
FROM tableName c
WHERE c.name = a.name AND
c.subject <= a.subject) AS rn
FROM TableName a
) aa
GROUP BY Name
SQLFiddle Demo
The above is an SQL way.
You need a PIVOT routine. Serach for this in the engine of your choice.
Some RDBMSs have this built in. There is an alternative using a CASE statement in the SELECT clause, for which there are many blog posts out there.
You can accomplish this in one statement using a combination of substring_index() and group_concat() like this (SQLfiddle)
SELECT DISTINCT s.name,
substring_index(p.subject_list, ',', 1) AS "subject_1",
IF(instr(p.subject_list, ','),
substring_index(p.subject_list, ',', -1),
NULL
) AS "subject_2"
FROM subjects s
JOIN (SELECT name, GROUP_CONCAT(subject) AS "subject_list"
FROM subjects
GROUP BY name
) p on p.name = s.name
;

MySql Impass - can't move forward

I currently have this sql statement that I wrote and it works but it's not quite what I want. I've been working on it for hours but can't seem to get any further.
select parent.id as parent_id, parent.subject as parent,s.id,s.subject from (select s.id, s.subject from subjects s where parent_id = 0) parent join subjects s on parent.id = s.parent_id order by parent.subject, s.subject
It's grabbing all the subjects and ordering correctly but I also want to return the parent subject (parent_id = 0) at the top of each grouping. This is because some parents may not have subjects underneath but I still need to return them. Also the ordering is off when I try to do it as I want the parent first then it's child subjects. Hope that makes sense but if not just ask.
Any help would be appreciated.
Thanks
Steve
You're talking about grouping sets of rows by their parent rows.
The only way I know how to do this in MySQL is using the GROUP_CONCAT() function which won't group the subjects by row, but rather create a grouped string.
Here's what you can do:
SELECT
a.id,
a.subject,
GROUP_CONCAT(CONCAT(b.id, ':::', b.subject) ORDER BY b.subject SEPARATOR '|||') AS subjectlist
FROM
subjects a
LEFT JOIN
subjects b ON a.id = b.parent_id
WHERE
a.parent_id = 0
GROUP BY
a.id,
a.subject
ORDER BY
a.subject
So this will give you a result set like:
id | subject | subjectlist
---------------------------------------------------------------------
2 | subj1 | 23:::childsubj1|||28:::childsubj4
3 | subj2 | 18:::childsubj8|||55:::childsubj16
4 | subj3 | NULL
Depending on what language you are using in your application, you may be able to "explode" the subjects string into arrays delimited first by ||| which separates each subject, then ::: which separates that subject's ID and name.
Obviously, the downside of this is you have to make sure that your child subject name does not contain either ||| or ::: or whichever delimiters you decide to use.
Edit: Experimentally, I came up with this alternative solution which may be closer to what you're looking for:
Try:
SELECT
c.subj,
c.id
FROM
(
SELECT
CONCAT('---> ', b.subject) AS subj,
b.id,
CONCAT(a.subject, b.subject) AS orderfactor
FROM
subjects a
INNER JOIN
subjects b ON a.id = b.parent_id
WHERE
a.parent_id = 0
UNION ALL
SELECT
subject AS subj,
id,
subject AS orderfactor
FROM
subjects
WHERE
parent_id = 0
) c
ORDER BY
c.orderfactor
This query should give you a result along the lines of:
subject | id |
----------------------------------------------------------
subj1 | 2 |
---> childsubj1 | 23 |
---> childsubj4 | 28 |
subj2 | 3 |
---> childsubj8 | 18 |
---> childsubj16 | 55 |
subj3 | 4 |
subj4 | 5 |
---> childsubj10 | 79 |

How to sort items in mysql based on data from another table?

I have the following tables:
word_list:
id | word
1 | ball
2 | car
3 | small
items_word_match:
itemid | wordid | in_title | in_description
1 | 1 | 1 | 0 //The word #1 occurs once in the title of the item
1 | 3 | 0 | 2 //The word #3 occurs twice in the title of the item
3 | 3 | 1 | 2
2 | 1 | 1 | 0
search:
wordid | importance
1 | 1
2 | 5
3 | 2 //word #3 is more important than the word #1 but less so than word #2
I want to sort the items based on the keywords from the search table and how important the keywords are.
And if the keyword is in the title the importance should increase by 1 and if the word appears 2 times the importance of the word should be importance*2
Neither of those answers from Denis or Johan are correct. Instead you could use this:
select
itemid,
sum(word_importance) as item_importance
from
(select
itemid,
search.wordid,
(
in_title * (importance + 1)
+ in_description * importance
) as word_importance
from
items_word_match,
search
where
i.wordid = s.wordid
)
group by itemid
As Johan pointed out, you need to add an order clause to the end, , order by item_importance desc
Feel a bit lazy today, so I'm just going to answer the question in the title:
How to sort items in mysql based on data from another table ?
You can sort the outcome of a query by any criterium you wish.
SELECT word_list.* FROM word_list
INNER JOIN search ON (search.wordid = wordlist.id)
ORDER BY search.importance, word_list.id DESC
Note that the JOIN needed to link the two tables together can have a profound effect on which rows in the word_list table are selected, but you need to do a JOIN somehow.
Otherwise MySQL will not know what the relationship between the two tables is and cannot sort the fields.
SELECT
i.itemid
, SUM( i.in_description * s.importance
+ i.in_title * ( s.importance + 1 )
)
AS item_importance
FROM
items_word_match i
LEFT JOIN
search s
ON s.wordid = i.wordid
GROUP BY
i.itemid
ORDER BY
item_importance DESC
CORRECTION:
I used LEFT JOIN catch the case when some words do not appear in the search table. But then the importance of those words seems appropriate to be 0 and not NULL, so the SUM should be changed into:
, SUM( i.in_description * COALESCE(s.importance, 0)
+ i.in_title * COALESCE(s.importance, 1)
)
your order by clause can contain fields from any of the tables:
select table1.*
from table1
join table2 using (table1_id)
order by table2.field, table1.field, etc.