Mysql query using group_concat and self referencing id in the table - mysql

Here is my table and sample data.
CREATE TABLE `sections` (
`section_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`parent_section_id` int(11) DEFAULT NULL,
PRIMARY KEY (`section_id`)
);
INSERT INTO `sections` (`section_id`, `name`, `parent_section_id`) VALUES
(1, 'City', NULL),
(2, 'Supplements', 4),
(3, 'News', 5),
(4, 'Sunday', 2),
(5, 'Monday', 2),
(6, 'Tuesday', 2),
(7, 'Wednesday', 2),
(8, 'Thursday', 2),
(9, 'Friday', 2),
(10, 'Saturday', 2),
(11, 'Home', 4),
(12, 'Games', 4),
(13, 'Sites', 5),
(14, 'Sports', 5),
(15, 'Cyber Space', 6);
parent_section_id is foreign key referencing to section_id in the same table which can have null if it doesn't belong to any other section.
How can I get the below output I have tried using group_concat function but it doesn't give the exact result. The parent_section_id is pointing to id from the same table. Should I use any other column to achieve the below output or use some other table to keep track of Sections which contains sub sections.
Please help me solve this problem or suggest any other approach
id, Name, SubSections
----------------------
1, 'City', null
2, 'Supplements', 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'
3, 'News', null
4, 'Sunday', 'Homes,Games'
5, 'Monday','Sites,Sports'
6, 'Tuesday', 'Cyber Space'
7, 'Wednesday', null
8, 'Thursday', null
9, 'Friday', null
10, 'Saturday', null
11, 'Home', null
12, 'Games', null
13, 'Site', null
14, 'Sports', null
15, 'Cyber Space',null
Here is sql fiddle link http://sqlfiddle.com/#!9/e9767/2
Final Query
select s1.section_id, s1.name, group_concat(s2.name) as subsections,
(select name from sections where section_id = s1.parent_section_id) as 'parentname'
from sections s1
left join sections s2 on s1.section_id = s2.parent_section_id
group by s1.section_id;

You can get the result you want by using a (left) self-join on section_id = parent_section_id like so:
select s1.section_id, s1.name, group_concat(s2.name) as subsections
from sections s1
left join sections s2 on s1.section_id = s2.parent_section_id
group by s1.section_id;
Sample SQL Fiddle

Related

after left-join result, need a countresult per user

I have managed to create a query, which even works.
SELECT voterID,vote,nick as player
FROM
trust LEFT JOIN players
ON trust.playerID=players.playerID
ORDER BY trust.vote DESC, trust.playerID DESC
This gives me a full list of all votes, but I want to SUM the votes per player, so i get 1 row per player, with 1 total amount of trustpoints.(can be positive or negative. +1 or -1 per voted, per voter)
The table trust:
CREATE TABLE `trust` (
`rowID` int(10) UNSIGNED NOT NULL,
`playerID` int(11) UNSIGNED NOT NULL,
`voterID` int(11) UNSIGNED NOT NULL,
`vote` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `trust` (`rowID`, `playerID`, `voterID`, `vote`) VALUES
(25, 2187, 1, 1),
(26, 23193, 1, 1),
(27, 2050, 1, 1),
(29, 3714, 1, 1),
(31, 1, 2187, 1),
(32, 30363, 29937, 1),
(33, 15837, 26102, 1),
(34, 30058, 26102, 1),
(35, 30539, 26102, -1),
(36, 28382, 26102, -1),
(37, 18692, 26102, 1),
(38, 6440, 14143, 1),
(39, 15069, 8306, 1),
(40, 2050, 2187, 1),
(41, 3233, 1, 1),
(42, 12664, 26102, 1),
(43, 30539, 2187, -1),
(44, 28382, 2187, -1),
(45, 30539, 1, -1),
(46, 10138, 1, 1);
Expecting result: a list of names and total SUM of votes
You can join the player table on an aggregate query of the votes:
SELECT nick AS player, sum_votes
FROM players p
JOIN (SELECT playerid, SUM(vote) AS sum_votes
FROM trust
GROUP BY playerid) t ON p.playerid = t.playerid
ORDER BY 2 DESC

How do I build a query to get the latest row per user where a third criteria is in a separate table?

I have three tables
CREATE TABLE `LineItems` (
`LineItemID` int NOT NULL,
`OrderID` int NOT NULL,
`ProductID` int NOT NULL
);
INSERT INTO `LineItems` (`LineItemID`, `OrderID`, `ProductID`) VALUES
(1, 1, 2),
(2, 1, 1),
(3, 2, 3),
(4, 2, 4),
(5, 3, 1),
(6, 4, 2),
(7, 5, 4),
(8, 5, 2),
(9, 5, 3),
(10, 6, 1),
(11, 6, 4),
(12, 7, 4),
(13, 7, 1),
(14, 7, 2),
(15, 8, 1),
(16, 9, 3),
(17, 9, 4),
(18, 10, 3);
CREATE TABLE `Orders` (
`OrderID` int NOT NULL,
`UserID` int NOT NULL,
`OrderDate` datetime NOT NULL
);
INSERT INTO `Orders` (`OrderID`, `UserID`, `OrderDate`) VALUES
(1, 21, '2021-05-01 00:00:00'),
(2, 21, '2021-05-03 00:00:00'),
(3, 24, '2021-05-06 00:00:00'),
(4, 23, '2021-05-12 00:00:00'),
(5, 21, '2021-05-14 00:00:00'),
(6, 22, '2021-05-16 00:00:00'),
(7, 23, '2021-05-20 00:00:00'),
(8, 21, '2021-05-22 00:00:00'),
(9, 24, '2021-05-23 00:00:00'),
(10, 23, '2021-05-26 00:00:00');
CREATE TABLE `Products` (
`ProductID` int NOT NULL,
`ProductTitle` VARCHAR(250) NOT NULL,
`ProductType` enum('doors','windows','flooring') NOT NULL
);
INSERT INTO `Products` (`ProductID`, `ProductTitle`, `ProductType`) VALUES
(1, 'French Doors','doors'),
(2, 'Sash Windows','windows'),
(3, 'Sliding Doors','doors'),
(4, 'Parquet Floor','flooring');
SQL Fiddle:
Orders - contains an order date and a user id
LineItems - Foreign key to the orders table, contains product ids that are in the order
Products - Contains details of the products (including if they are a door, window, or flooring)
I have figured out how to get the latest order per user with
SELECT O.* FROM Orders O LEFT JOIN Orders O2
ON O2.UserID=O.UserID AND O.OrderDate < O2.OrderDate
WHERE O2.OrderDate IS NULL;
This works fine and is included in the SQL fiddle, along with a query that returns a complete picture for reference.
I am trying to figure out how to get the latest order with flooring per user, but I'm not having any luck.
In the SQL fiddle linked above, the intended output for what I am after would be
OrderID | UserID | OrderDate
6 | 22 | 2021-05-16T00:00:00Z
5 | 21 | 2021-05-14T00:00:00Z
9 | 24 | 2021-05-23T00:00:00Z
7 | 23 | 2021-05-20T00:00:00Z
EDIT: To clarify, in the intended result, two rows (for users 21 and 23) are different than in the query that gets just latest order per user. This is because order IDs 8 and 10 (from the latest order per user query) do not include flooring. The intended query has to find the latest order with flooring from each user to return in the result set.
You need to add the LineItems and Products tables to your query to find orders where flooring was purchased:
SELECT DISTINCT O.*
FROM Orders O
LEFT JOIN Orders O2
ON O2.UserID=O.UserID AND
O.OrderDate < O2.OrderDate
INNER JOIN LineItems i
ON i.OrderID = O.OrderID
INNER JOIN Products p
ON p.ProductID = i.ProductID
WHERE O2.OrderDate IS NULL AND
p.ProductType = 'flooring'
db<>fiddle here

MySQL - Query not returning proper results

CREATE TABLE `swipes` (
`swp_id` bigint(20) NOT NULL,
`swp_by` bigint(20) NOT NULL,
`swp_to` bigint(20) NOT NULL,
`swp_type` varchar(255) NOT NULL,
`swp_status` enum('requested','accepted','declined') NOT NULL,
`swp_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `swipes` (`swp_id`, `swp_by`, `swp_to`, `swp_type`, `swp_status`, `swp_date`) VALUES
(1, 8, 11, 'top', 'accepted', '2020-04-18 20:48:45'),
(2, 1, 11, 'right', 'accepted', '2020-04-18 20:41:49'),
(3, 12, 1, 'right', 'accepted', '2020-04-18 20:41:49'),
(4, 13, 1, 'right', 'accepted', '2020-04-18 20:41:49'),
(5, 1, 14, 'right', 'accepted', '2020-04-18 20:41:49'),
(6, 1, 15, 'top', 'accepted', '2020-04-18 20:41:49');
CREATE TABLE `messages` (
`msg_id` bigint(20) NOT NULL,
`msg_from` bigint(20) NOT NULL,
`msg_to` bigint(20) NOT NULL,
`msg_message` longtext NOT NULL,
`msg_seen` enum('yes','no') NOT NULL DEFAULT 'no',
`msg_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `messages` (`msg_id`, `msg_from`, `msg_to`, `msg_message`, `msg_seen`, `msg_time`) VALUES
(1, 11, 1, 'How are you?', 'yes', '2020-04-14 21:01:05'),
(3, 1, 11, 'I am fine.. you?', 'no', '2020-04-14 20:54:07'),
(4, 1, 8, 'How are you?', 'yes', '2020-04-14 21:01:05'),
(5, 8, 1, 'I am good... You say?', 'yes', '2020-04-14 21:13:34'),
(6, 1, 11, 'Thik hun... Tum batao..', 'yes', '2020-04-14 21:16:05'),
(7, 11, 1, 'Okay', 'yes', '2020-04-16 09:16:39'),
(8, 8, 1, 'Yes, it\'s a good idea.', 'yes', '2020-04-16 09:16:39'),
(9, 1, 8, 'Thought so.. Would you like to join?', 'yes', '2020-04-16 09:23:39'),
(10, 8, 1, 'Are you there?', 'yes', '2020-04-23 11:57:39'),
(12, 8, 1, 'Would you like to join?', 'yes', '2020-04-23 10:42:27'),
(13, 1, 11, 'We will arrange things for you :)', 'yes', '2020-04-23 10:59:04');
Fiddle: DB FIDDLE
In the fiddle above my query is returning correct data but it seems to eliminate results when 1 is present in multiple records of swp_by in swipes table. At first I thought it was because of GROUP BY swipes.swp_by but I removed it and it seemed like it wasn't the issue so I placed it back. When you run the query you see that currently the query returns result for swp_id 2, 3 & 4 but not for 5 & 6. They are eliminated and it's because in swp_by 1 occurred in swp_id 2 once. I want the query to return the results for 5 & 6 as well.
Query
SELECT
swp_id,
swp_by,
swp_to,
msg_from,
msg_to,
msg_message,
GREATEST(MAX(msg_time), swipes.swp_date) AS msgdate,
COUNT(msg_id) AS msgcnt
FROM
swipes
LEFT JOIN
(SELECT
*
FROM
messages
ORDER BY msg_time DESC) messages ON ((messages.msg_from = swipes.swp_by
AND messages.msg_to = swipes.swp_to)
OR (messages.msg_from = swipes.swp_to
AND messages.msg_to = swipes.swp_by))
WHERE
(swipes.swp_by = 1 OR swipes.swp_to = 1)
AND swipes.swp_status = 'accepted'
GROUP BY swipes.swp_by
ORDER BY GREATEST(MAX(messages.msg_time),
MAX(swipes.swp_date)) DESC
What is this all about?
I am setting up a chatting system and users who are matched are able chat with each other. swipes stores the matches and messages are the transacted messages between the users. With this query I am trying to set up the home list of matched users to chat with where you tap/click a user and the chat box appears (will make that later). I thought just giving a brief about the project might help in understanding the problem.
I post my asnwer here the fiddle doesn't give the right link
no got it https://www.db-fiddle.com/f/2yKt6d5RWngXVYJKPGZL6m/2
SELECT
swp_id,
swp_by,
swp_to,
msg_from,
msg_to,
msg_message ,
GREATEST(MAX(msg_time), swipes.swp_date) AS msgdate,
COUNT(msg_id) AS msgcnt
FROM
swipes
LEFT JOIN
(SELECT
*
FROM
messages
ORDER BY msg_time DESC) messages
ON (messages.msg_from = swipes.swp_by
AND messages.msg_to = swipes.swp_to)
OR
(messages.msg_from = swipes.swp_to
AND messages.msg_to = swipes.swp_by)
WHERE
(swipes.swp_by = 1 OR swipes.swp_to = 1)
AND swipes.swp_status = 'accepted'
GROUP BY swipes.swp_by,swipes.swp_to
ORDER BY GREATEST(MAX(messages.msg_time),
MAX(swipes.swp_date)) DESC

Select rows grouped by a column having max aggregate

Given the following data set, how would I find the email addresses that were references for the most ApplicationIDs that have an "Accepted" decision?
CREATE TABLE IF NOT EXISTS `EmailReferences` (
`ApplicationID` INT NOT NULL,
`Email` VARCHAR(45) NOT NULL,
PRIMARY KEY (`ApplicationID`, `Email`)
);
INSERT INTO EmailReferences (ApplicationID, Email)
VALUES
(1, 'ref10#test.org'), (1, 'ref11#test.org'), (1, 'ref12#test.org'),
(2, 'ref20#test.org'), (2, 'ref21#test.org'), (2, 'ref22#test.org'),
(3, 'ref11#test.org'), (3, 'ref31#test.org'), (3, 'ref32#test.org'),
(4, 'ref40#test.org'), (4, 'ref41#test.org'), (4, 'ref42#test.org'),
(5, 'ref50#test.org'), (5, 'ref51#test.org'), (5, 'ref52#test.org'),
(6, 'ref60#test.org'), (6, 'ref11#test.org'), (6, 'ref62#test.org'),
(7, 'ref70#test.org'), (7, 'ref71#test.org'), (7, 'ref72#test.org'),
(8, 'ref10#test.org'), (8, 'ref81#test.org'), (8, 'ref82#test.org')
;
CREATE TABLE IF NOT EXISTS `FinalDecision` (
`ApplicationID` INT NOT NULL,
`Decision` ENUM('Accepted', 'Denied') NOT NULL,
PRIMARY KEY (`ApplicationID`)
);
INSERT INTO FinalDecision (ApplicationID, Decision)
VALUES
(1, 'Accepted'), (2, 'Denied'),
(3, 'Accepted'), (4, 'Denied'),
(5, 'Denied'), (6, 'Denied'),
(7, 'Denied'), (8, 'Accepted')
;
Fiddle of same:http://sqlfiddle.com/#!9/03bcf2/1
Initially, I was using LIMIT 1 and ORDER BY CountDecision DESC, like so:
SELECT er.email, COUNT(fd.Decision) AS CountDecision
FROM EmailReferences AS er
JOIN FinalDecision AS fd ON er.ApplicationID = fd.ApplicationID
WHERE fd.Decision = 'Accepted'
GROUP BY er.email
ORDER BY CountDecision DESC
LIMIT 1
;
However, it occurred to me that I could have multiple email addresses that referred different "most accepted" decisions (i.e., a tie, so to speak), and those would be filtered out (is that the right phrasing?) with the LIMIT keyword.
I then tried a variation on the above query, replacing the ORDER BY and LIMIT lines with:
HAVING MAX(CountDecision)
But I realized that that's only half a statement: MAX(CountDecision) needs to be compared to something. I just don't know what.
Any pointers would be much appreciated. Thanks!
Note: this is for a homework assignment.
Update: To be clear, I'm trying to find value and count of Emails from EmailReferences. However, I only want rows that have FinalDecision.Decision = 'Accepted' (on matching ApplicantIDs). Based on my data, the result should be:
Email | CountDecision
---------------+--------------
ref10#test.org | 2
ref11#test.org | 2
For example...
SELECT a.*
FROM
( SELECT x.email
, COUNT(*) total
FROM emailreferences x
JOIN finaldecision y
ON y.applicationid = x.applicationid
WHERE y.decision = 'accepted'
GROUP
BY x.email
) a
JOIN
( SELECT COUNT(*) total
FROM emailreferences x
JOIN finaldecision y
ON y.applicationid = x.applicationid
WHERE y.decision = 'accepted'
GROUP
BY x.email
ORDER
BY total DESC
LIMIT 1
) b
ON b.total = a.total;
MySQL still lack window functions, but when version 8 is production ready, this becomes easier. So for fuure reference, or for those databases like Mariadb that already have window functions:
CREATE TABLE IF NOT EXISTS `EmailReferences` (
`ApplicationID` INT NOT NULL,
`Email` VARCHAR(45) NOT NULL,
PRIMARY KEY (`ApplicationID`, `Email`)
);
INSERT INTO EmailReferences (ApplicationID, Email)
VALUES
(1, 'ref10#test.org'), (1, 'ref11#test.org'), (1, 'ref12#test.org'),
(2, 'ref20#test.org'), (2, 'ref21#test.org'), (2, 'ref22#test.org'),
(3, 'ref30#test.org'), (3, 'ref31#test.org'), (3, 'ref32#test.org'),
(4, 'ref40#test.org'), (4, 'ref41#test.org'), (4, 'ref42#test.org'),
(5, 'ref50#test.org'), (5, 'ref51#test.org'), (5, 'ref52#test.org'),
(6, 'ref60#test.org'), (6, 'ref11#test.org'), (6, 'ref62#test.org'),
(7, 'ref70#test.org'), (7, 'ref71#test.org'), (7, 'ref72#test.org'),
(8, 'ref10#test.org'), (8, 'ref81#test.org'), (8, 'ref82#test.org')
;
CREATE TABLE IF NOT EXISTS `FinalDecision` (
`ApplicationID` INT NOT NULL,
`Decision` ENUM('Accepted', 'Denied') NOT NULL,
PRIMARY KEY (`ApplicationID`)
);
INSERT INTO FinalDecision (ApplicationID, Decision)
VALUES
(1, 'Accepted'), (2, 'Denied'),
(3, 'Accepted'), (4, 'Denied'),
(5, 'Denied'), (6, 'Denied'),
(7, 'Denied'), (8, 'Accepted')
;
select email, CountDecision
from (
SELECT er.email, COUNT(fd.Decision) AS CountDecision
, max(COUNT(fd.Decision)) over() maxCountDecision
FROM EmailReferences AS er
JOIN FinalDecision AS fd ON er.ApplicationID = fd.ApplicationID
WHERE fd.Decision = 'Accepted'
GROUP BY er.email
) d
where CountDecision = maxCountDecision
email | CountDecision
:------------- | ------------:
ref10#test.org | 2
dbfiddle here

SELECT query for TableA and TableB IF TableB.col value (0 OR 1) I create new columns for 0 and 1

I have a Table pictures
create table pictures (
picture_id int(10) unsigned NOT NULL AUTO_INCREMENT,
mall_id float NOT NULL,
shop_id float NOT NULL,
picture_islogo int(11) NOT NULL ,
picture_path varchar(255) NOT NULL,
PRIMARY KEY (picture_id)
) ;
Sample Data for pictures
INSERT INTO pictures VALUES
(1, -1, 1, 1, 'photo.jpg'),
(2, -1, 2, 1, 'photo.jpg'),
(3, -1, 3, 1, 'photo.jpg'),
(4, -1, 4, 1, 'photo.jpg'),
(5, -1, 5, 1, 'photo.jpg'),
(6, -1, 6, 1, 'photo.jpg'),
(7, -1, 7, 1, 'photo.jpg'),
(8, -1, 8, 1, 'photo.jpg'),
(9, -1, 9, 1, 'photo.jpg'),
(10, -1, 10, 1, 'photo.jpg'),
(11, -1, 11, 1, 'photo.jpg'),
(12, -1, 12, 1, 'photo.jpg'),
(13, -1, 13, 1, 'photo.jpg'),
(14, -1, 13, 0, 'photo.jpg');
and other table malls
create table malls (
mall_id float NOT NULL AUTO_INCREMENT,
user_id float NOT NULL,
mall_displaysname varchar(255) NOT NULL,
mall_description text NOT NULL,
mall_contact varchar(14) NOT NULL,
mall_logo_picture_id int(11) NOT NULL,
mall_background_picture_id int(11) NOT NULL,
PRIMARY KEY (mall_id)
);
Sample Data for malls
INSERT INTO malls VALUES
(1, 2, 'mall', 'description', '+60 12 3456789', 14, 36),
(2, 5, 'mall 2', 'description', '+60 12 3456789', 15, 37),
(3, 6, 'mall 3', 'description ', '+60 12 3456789', 16, 38),
(4, 13, 'Multimedia University', 'description ', '+60 12 3456789', 17, 39),
(5, 18, 'Setia Walk', 'description ', '+60 12 3456789', 18, 40),
(6, 20, 'Ampang Point', 'description ', '+60 12 3456789', 19, 41),
(7, 21, 'Alamanda Plaza', 'description ', '+60 12 3456789', 20, 42),
(8, 22, 'Subang Parade', 'description ', '+60 12 3456789', 21, 43),
(9, 26, 'مجمع العرب - جدة', 'description ', '+60 12 3456789', 22, 44);
Where mall_background_picture_id and mall_background_picture_id reference to pictures.picture_id and Depend on the value of pictures.picture_islogo (0: Logo, 1:background or others)
i want a query to that returns the pictures.picture_path depends on the value of pictures.picture_islogo (0: Logo, 1:background or others)
the data that I need to get
mall_id , mall_displaysname, mall_logo, mall_background , mall_description, and mall_contact
Where mall_logo is the photo_path of the condition
pictures.picture_islogo = 1
and same thing with **mall_background** but
picture_islogo = 0
AND
mall_logo_picture_id = picture_id
Put the extra condition into the join condition:
select * -- you can chose what columns you want
from malls m
left join pictures pl on m.mall_logo_picture_id = pl.picture_id
and pl.picture_isLogo = 1
left join pictures pb on m.mall_background_picture_id = pb.picture_id
and pb.picture_isLogo = 0
To have left joins, the extra conditions must be in the join condition, which is evaluated as the join is being made.
If you put them in the where clause, which is evaluated after the join is made, you force the outer join to be an inner join, because the join must be successful fur the extra condition to be true.