Why delete query only delete one record - mysql

Hi I’ve got the folowing query:
DELETE tickets, archive, files
FROM tickets
LEFT JOIN ticket_files
ON ticket_files.ticket_id = tickets.ticket_id
LEFT JOIN archive
ON archive.document_id = ticket_files.document_id
LEFT JOIN files
ON files.file_id = ticket_files.file_id
WHERE tickets.ticket_id = 21
When the ticket doesn’t have any record in the junction table ticket_files then the ticket is deleted correctly but if there is more than one record in the ticket_files then only one record is deleted from the tables archive and files. How can i make sure all the joined records are deleted also from archive and files? many thanks
This is the database structure. As you can see the ticket with ID 1 has got two files associated in the ticket_files table but ticket with ID 2 doesn't have any files associated.
-- phpMyAdmin SQL Dump
-- version 5.1.0
-- https://www.phpmyadmin.net/
--
-- Host: localhost:8889
-- Generation Time: Mar 28, 2022 at 07:35 PM
-- Server version: 5.7.34
-- PHP Version: 8.0.8
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
--
-- Database: `test`
--
-- --------------------------------------------------------
--
-- Table structure for table `archive`
--
CREATE TABLE `archive` (
`document_id` int(11) NOT NULL,
`document_sent_by` int(11) NOT NULL,
`document_description` varchar(255) NOT NULL,
`document_category` int(11) NOT NULL,
`document_status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=public 0=draft',
`document_featured` tinyint(1) NOT NULL DEFAULT '0' COMMENT '0=no 1=yes',
`document_note` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `archive`
--
INSERT INTO `archive` (`document_id`, `document_sent_by`, `document_description`, `document_category`, `document_status`, `document_featured`, `document_note`) VALUES
(23, 1, 'File one', 7, 1, 0, 'File one'),
(24, 1, 'File two', 7, 1, 0, 'File two');
-- --------------------------------------------------------
--
-- Table structure for table `files`
--
CREATE TABLE `files` (
`file_id` int(11) NOT NULL,
`file_name` varchar(255) NOT NULL,
`file_type` varchar(255) NOT NULL,
`file_size` varchar(255) NOT NULL,
`file_date` datetime DEFAULT CURRENT_TIMESTAMP,
`file_category` int(11) NOT NULL,
`file_status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=public 0=draft',
`file_path` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `files`
--
INSERT INTO `files` (`file_id`, `file_name`, `file_type`, `file_size`, `file_date`, `file_category`, `file_status`, `file_path`) VALUES
(23, '1648496062', 'application/pdf', '9514', '2022-03-02 00:00:00', 7, 1, '/docs/1648496062.pdf'),
(24, '1648496079', 'application/pdf', '146367', '2022-03-09 00:00:00', 7, 1, '/docs/1648496079.pdf');
-- --------------------------------------------------------
--
-- Table structure for table `tickets`
--
CREATE TABLE `tickets` (
`ticket_id` int(11) NOT NULL,
`ticket_sent_by` int(11) NOT NULL,
`building_id` int(11) NOT NULL,
`ticket_subject` varchar(255) NOT NULL,
`ticket_object` text NOT NULL,
`ticket_priority` tinyint(1) NOT NULL,
`ticket_status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=aperto 2=lavorazione 3=chiuso',
`ticket_comments` tinyint(1) NOT NULL DEFAULT '1' COMMENT '0=no 1=yes',
`ticket_visibility` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=public 0=draft',
`ticket_featured` tinyint(1) NOT NULL DEFAULT '0' COMMENT '0=no 1=yes',
`ticket_private` tinyint(1) NOT NULL DEFAULT '0' COMMENT ' 0=no 1=yes ',
`ticket_open_time` datetime DEFAULT CURRENT_TIMESTAMP,
`ticket_edit_time` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `tickets`
--
INSERT INTO `tickets` (`ticket_id`, `ticket_sent_by`, `building_id`, `ticket_subject`, `ticket_object`, `ticket_priority`, `ticket_status`, `ticket_comments`, `ticket_visibility`, `ticket_featured`, `ticket_private`, `ticket_open_time`, `ticket_edit_time`) VALUES
(1, 1, 13, 'Ticket with files', '<p>this ticket has files<br /></p>', 1, 1, 0, 1, 0, 0, '2022-03-28 20:33:59', NULL),
(2, 1, 13, 'Ticket with no files', '<p>ticket with no files<br /></p>', 1, 1, 0, 1, 0, 0, '2022-03-28 20:35:02', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `ticket_files`
--
CREATE TABLE `ticket_files` (
`ticket_id` int(11) NOT NULL,
`document_id` int(11) NOT NULL,
`file_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `ticket_files`
--
INSERT INTO `ticket_files` (`ticket_id`, `document_id`, `file_id`) VALUES
(1, 23, 23),
(1, 24, 24);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `archive`
--
ALTER TABLE `archive`
ADD PRIMARY KEY (`document_id`);
--
-- Indexes for table `files`
--
ALTER TABLE `files`
ADD PRIMARY KEY (`file_id`);
--
-- Indexes for table `tickets`
--
ALTER TABLE `tickets`
ADD PRIMARY KEY (`ticket_id`);
--
-- Indexes for table `ticket_files`
--
ALTER TABLE `ticket_files`
ADD KEY `ticket_id` (`ticket_id`),
ADD KEY `document_id` (`document_id`) USING BTREE,
ADD KEY `file_id` (`file_id`);
-- AUTO_INCREMENT for table `archive`
--
ALTER TABLE `archive`
MODIFY `document_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=25;
--
-- AUTO_INCREMENT for table `files`
--
ALTER TABLE `files`
MODIFY `file_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=25;
--
-- AUTO_INCREMENT for table `tickets`
--
ALTER TABLE `tickets`
MODIFY `ticket_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- Constraints for table `ticket_files`
--
ALTER TABLE `ticket_files`
ADD CONSTRAINT `ticket_files_ibfk_1` FOREIGN KEY (`ticket_id`) REFERENCES `tickets` (`ticket_id`) ON DELETE CASCADE,
ADD CONSTRAINT `ticket_files_ibfk_2` FOREIGN KEY (`document_id`) REFERENCES `archive` (`document_id`) ON DELETE CASCADE,
ADD CONSTRAINT `ticket_files_ibfk_3` FOREIGN KEY (`file_id`) REFERENCES `files` (`file_id`) ON DELETE CASCADE;
COMMIT;

We can add ticket_files to the list of the tables in the DELETE:
select * from ticket_files;
ticket_id | document_id | file_id
--------: | ----------: | ------:
1 | 23 | 23
1 | 24 | 24
DELETE tickets, archive, files, ticket_files
FROM tickets
LEFT JOIN ticket_files
ON ticket_files.ticket_id = tickets.ticket_id
LEFT JOIN archive
ON archive.document_id = ticket_files.document_id
LEFT JOIN files
ON files.file_id = ticket_files.file_id
WHERE tickets.ticket_id = 1
✓
select * from ticket_files;
ticket_id | document_id | file_id
--------: | ----------: | ------:
db<>fiddle here

Related

how to gather data from all the six tabels in mysql

I tried Inner join, however i m not able to figure out what is wrong i m doing.
How can I query data from all the 6 tables in the blue box.
The studentprofile table is what is the link between the other 5 tables in the blue region.
I ran this query and this showed me all the data.
select * from users, roles_assigned,studentprofile,schoolwithusers;
Problem I am facing is that I need only filted data for user who are students and school name and student profile
Please Help.
here is my sql code.
--
-- Database: `onlinemarksheets`
--
-- --------------------------------------------------------
--
-- Table structure for table `exams`
--
CREATE TABLE `exams` (
`id` int(11) NOT NULL,
`examtye_id` int(11) DEFAULT NULL,
`schooluser_id` int(11) DEFAULT NULL,
`duration_to` date DEFAULT NULL,
`duration_from` date DEFAULT NULL,
`year` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `examtype`
--
CREATE TABLE `examtype` (
`id` int(11) NOT NULL,
`type` enum('Mid-Term','Half-yearly','Yearly') DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `examtype`
--
INSERT INTO `examtype` (`id`, `type`) VALUES
(1, 'Mid-Term'),
(2, 'Half-yearly'),
(3, 'Yearly');
-- --------------------------------------------------------
--
-- Table structure for table `marks`
--
CREATE TABLE `marks` (
`id` int(11) NOT NULL,
`exam_id` int(11) DEFAULT NULL,
`name` varchar(45) DEFAULT NULL,
`marks_obtained` int(11) DEFAULT NULL,
`marks_total` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `roles`
--
CREATE TABLE `roles` (
`id` int(11) NOT NULL,
`type` enum('Admin','Teacher','Student') DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `roles`
--
INSERT INTO `roles` (`id`, `type`) VALUES
(1, 'Admin'),
(2, 'Teacher'),
(3, 'Student');
-- --------------------------------------------------------
--
-- Table structure for table `roles_assigned`
--
CREATE TABLE `roles_assigned` (
`id` int(11) NOT NULL,
`role_id` int(11) DEFAULT NULL,
`user_id` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `roles_assigned`
--
INSERT INTO `roles_assigned` (`id`, `role_id`, `user_id`) VALUES
(1, 1, 1),
(2, 2, 2),
(3, 3, 3),
(4, 3, 4),
(5, 3, 5),
(6, 3, 6),
(7, 1, 1),
(8, 2, 2),
(9, 3, 3),
(10, 3, 4),
(11, 3, 5),
(12, 3, 6);
-- --------------------------------------------------------
--
-- Table structure for table `schools`
--
CREATE TABLE `schools` (
`id` int(11) NOT NULL,
`schoolname` varchar(45) DEFAULT NULL,
`school_email` varchar(45) DEFAULT NULL,
`school_phone` varchar(45) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `schools`
--
INSERT INTO `schools` (`id`, `schoolname`, `school_email`, `school_phone`) VALUES
(1, 'D.A.V Public school', 'info#davschool.com', '789456123'),
(2, 'saraswati Public school', 'info#saraswatischool.com', '9998887774'),
(3, 'S.G.R.R Public School', 'Info#sgrr.com', '54245645125'),
(4, 'Sun Valley Public', 'info#sunvalley.com', '23423423424'),
(5, 'Marshal Public school', 'info#marshalschool.com', '23482728347');
-- --------------------------------------------------------
--
-- Table structure for table `schoolwithusers`
--
CREATE TABLE `schoolwithusers` (
`id` int(11) NOT NULL,
`school_id` int(11) DEFAULT NULL,
`studentprofile_id` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `schoolwithusers`
--
INSERT INTO `schoolwithusers` (`id`, `school_id`, `studentprofile_id`) VALUES
(1, 1, 3),
(2, 3, 4);
-- --------------------------------------------------------
--
-- Table structure for table `studentprofile`
--
CREATE TABLE `studentprofile` (
`id` int(11) NOT NULL,
`user_id_fk` int(11) DEFAULT NULL,
`rollno` int(11) DEFAULT NULL,
`dob` date DEFAULT NULL,
`attendence` int(11) DEFAULT NULL,
`class` int(11) DEFAULT NULL,
`section` enum('A','B') DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `studentprofile`
--
INSERT INTO `studentprofile` (`id`, `user_id_fk`, `rollno`, `dob`, `attendence`, `class`, `section`) VALUES
(1, 3, 22, '2022-01-21', 60, 1, 'A'),
(2, 4, 21, '2012-01-04', 45, 1, 'A'),
(3, 4, 1, '2012-01-04', 100, 3, 'B'),
(4, 5, 30, '2007-04-26', 45, 3, 'B'),
(5, 6, 2, '2022-01-19', 50, 6, 'B');
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`fname` varchar(45) DEFAULT NULL,
`lname` varchar(45) DEFAULT NULL,
`email` varchar(45) DEFAULT NULL,
`password` varchar(45) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `fname`, `lname`, `email`, `password`) VALUES
(1, 'Shashank', 'Naithani', 'shashank8036#gmail.com', 'lol123'),
(2, 'Kuldeep', 'Negi', 'negikuldeep#gmail.com', 'lop123'),
(3, 'Arpit', 'Thakut', 'Aptha#gmail.com', 'arp123'),
(4, 'Ankit', 'Barthwal', 'ankitbarth#gmail.com', 'ankit123'),
(5, 'Mukesh', 'Thakur', 'sasdb#gmail.com', 'sha123'),
(6, 'Arjun', 'Negi', 'sasdb#gmail.com', 'sha123');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `exams`
--
ALTER TABLE `exams`
ADD PRIMARY KEY (`id`),
ADD KEY `examtye_id` (`examtye_id`) USING BTREE,
ADD KEY `schooluser_id` (`schooluser_id`);
--
-- Indexes for table `examtype`
--
ALTER TABLE `examtype`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `marks`
--
ALTER TABLE `marks`
ADD PRIMARY KEY (`id`),
ADD KEY `exam_id` (`exam_id`);
--
-- Indexes for table `roles`
--
ALTER TABLE `roles`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `roles_assigned`
--
ALTER TABLE `roles_assigned`
ADD PRIMARY KEY (`id`),
ADD KEY `role_id` (`role_id`) USING BTREE,
ADD KEY `user_id` (`user_id`) USING BTREE;
--
-- Indexes for table `schools`
--
ALTER TABLE `schools`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `schoolwithusers`
--
ALTER TABLE `schoolwithusers`
ADD PRIMARY KEY (`id`),
ADD KEY `school_id` (`school_id`) USING BTREE,
ADD KEY `studentprofile_id` (`studentprofile_id`);
--
-- Indexes for table `studentprofile`
--
ALTER TABLE `studentprofile`
ADD PRIMARY KEY (`id`),
ADD KEY `user_id_idx` (`user_id_fk`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `exams`
--
ALTER TABLE `exams`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `examtype`
--
ALTER TABLE `examtype`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `marks`
--
ALTER TABLE `marks`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `roles`
--
ALTER TABLE `roles`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `roles_assigned`
--
ALTER TABLE `roles_assigned`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13;
--
-- AUTO_INCREMENT for table `schools`
--
ALTER TABLE `schools`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `schoolwithusers`
--
ALTER TABLE `schoolwithusers`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `studentprofile`
--
ALTER TABLE `studentprofile`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `exams`
--
ALTER TABLE `exams`
ADD CONSTRAINT `examtye_id` FOREIGN KEY (`examtye_id`) REFERENCES `examtype` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `schooluser_id` FOREIGN KEY (`schooluser_id`) REFERENCES `schoolwithusers` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `marks`
--
ALTER TABLE `marks`
ADD CONSTRAINT `exam_id` FOREIGN KEY (`exam_id`) REFERENCES `exams` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `roles_assigned`
--
ALTER TABLE `roles_assigned`
ADD CONSTRAINT `role_id` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `schoolwithusers`
--
ALTER TABLE `schoolwithusers`
ADD CONSTRAINT `school_id` FOREIGN KEY (`school_id`) REFERENCES `schools` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `studentprofile_id` FOREIGN KEY (`studentprofile_id`) REFERENCES `studentprofile` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `studentprofile`
--
ALTER TABLE `studentprofile`
ADD CONSTRAINT `user_id_fk` FOREIGN KEY (`user_id_fk`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
COMMIT;
You have to join each table on the primary key/foreign key. Some of the sample data is not quite correct because you have duplicate combinations of student_id and roles_id values in the roles_assigned table. Be sure to list the column names you need instead of *.
select *
from users
INNER JOIN roles_assigned ON users.id = roles_assigned.user_id
INNER JOIN roles ON roles.id = roles_assigned.role_id
INNER JOIN studentprofile on studentprofile.id = users.id
INNER JOIN schoolwithusers on schoolwithusers.studentprofile_id =
studentprofile.id
INNER JOIN schools ON schools.id = schoolwithusers.school_id
WHERE roles.type = 'Student';

converting MySQL syntax to PostgreSQL

So I designed a Bank database in MySQL, and now I want to convert some syntax to PostgreSQL
this is my account and branch table :
CREATE TABLE `account` (
`accountnumber` int(80) NOT NULL,
`balance` text COLLATE utf8_bin NOT NULL,
`date` date NOT NULL,
`time` time NOT NULL,
`branchID` int(25) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
CREATE TABLE `branch` (
`branchID` int(25) NOT NULL,
`bName` varchar(50) COLLATE utf8_bin NOT NULL,
`bCity` varchar(50) COLLATE utf8_bin NOT NULL,
`assests` bigint(20) NOT NULL,
`mainbankID` int(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
I converted it already, but I have problems with these parts:
ALTER TABLE `account`
ADD PRIMARY KEY (`accountnumber`),
ADD KEY `branchID` (`branchID`);
ALTER TABLE `account`
ADD CONSTRAINT `account_ibfk_1` FOREIGN KEY (`branchID`) REFERENCES `branch` (`branchID`);
for example, I tried to write the first one like this, and I got errors:
ALTER TABLE account
ADD PRIMARY KEY (accountnumber),
ADD KEY branchID (branchID);
and I got this error :
type "branchid" does not exist
and here's my piece of code that I converted and working in PostgreSQL :
--
-- Database: `bank`
--
-- --------------------------------------------------------
--
-- Table structure for table account
--
CREATE TABLE account (
accountnumber INTEGER NOT NULL,
balance text NOT NULL,
date date NOT NULL,
time time NOT NULL,
branchID INTEGER NOT NULL
) ;
--
-- Dumping data for table `account`
--
INSERT INTO account (accountnumber, balance, date, time, branchID) VALUES
(1132, 'توضیحات ترازنامه', '2021-07-12', '00:00:03', 516),
(1792, 'توضیحات ترازنامه', '2020-05-29', '11:17:27', 516),
(5130, 'توضیحات ترازنامه', '2016-02-23', '13:18:00', 123),
(7123, 'توضیحات ترازنامه', '2011-11-16', '10:25:00', 124),
(8210, 'توضیحات ترازنامه', '2019-01-11', '16:20:06', 215);
-- --------------------------------------------------------
--
-- Table structure for table `borrower`
--
CREATE TABLE borrower (
customerID INTEGER NOT NULL,
loanID INTEGER NOT NULL
) ;
--
-- Dumping data for table `borrower`
--
INSERT INTO borrower (customerID, loanID) VALUES
(7951, 357),
(1089, 357);
-- --------------------------------------------------------
--
-- Table structure for table `branch`
--
CREATE TABLE branch (
branchID INTEGER NOT NULL,
bName varchar(50) NOT NULL,
bCity varchar(50) NOT NULL,
assests bigint NOT NULL,
mainbankID INTEGER NOT NULL
) ;
--
-- Dumping data for table `branch`
--
INSERT INTO branch (branchID, bName, bCity, assests, mainbankID) VALUES
(123, 'سعادت اباد', 'تهران', 250000000, 1111),
(124, 'تجریش', 'همدان ', 5842000, 2222),
(215, 'خیابان قیام', 'یزد', 700000000, 2222),
(391, 'نقش جهان', 'اصفهان', 20100000, 1111),
(516, 'میرداماد', 'تهران', 953200000, 1111);
-- --------------------------------------------------------
--
-- Table structure for table `customer`
--
CREATE TABLE customer (
customerID INTEGER NOT NULL,
CName varchar(78) NOT NULL,
cphonenumber INTEGER NOT NULL,
cCity varchar(50) NOT NULL,
caddress text NOT NULL,
cage INTEGER NOT NULL
) ;
--
-- Dumping data for table `customer`
--
INSERT INTO customer (customerID, CName, cphonenumber, cCity, caddress, cage) VALUES
(412, 'معین سپهری', 387496, 'تهران', 'تهران شهرک غرب', 27),
(1089, 'سحر مقدم', 3254896, 'اصفهان', 'اصفهان پل خواجوو', 32),
(7951, 'ددا رضوی', 36232323, 'تهران', 'تهران شهرک اندیشه مجتمع رز', 26),
(463241, 'محمد فلاح', 3456213, 'یزد', 'یزد خیابان کاشانی کوچه علوی', 50);
-- --------------------------------------------------------
--
-- Table structure for table `depositor`
--
CREATE TABLE depositor (
customerID INTEGER NOT NULL,
accountnumber INTEGER NOT NULL
) ;
--
-- Dumping data for table `depositor`
--
INSERT INTO depositor (customerID, accountnumber) VALUES
(7951, 7123),
(463241, 5130),
(412, 1132),
(463241, 1132),
(1089, 1132);
-- --------------------------------------------------------
--
-- Table structure for table `employee`
--
CREATE TABLE employee (
EmployeeID INTEGER NOT NULL,
Employeework varchar(100) NOT NULL,
Employeename varchar(25) NOT NULL,
aphonenumber INTEGER NOT NULL,
Employmentyear smallint NOT NULL,
eaddress text NOT NULL,
esalary INTEGER NOT NULL,
branchID INTEGER NOT NULL
) ;
--
-- Dumping data for table `employee`
--
CREATE TABLE mainbank (
mainbankID INTEGER NOT NULL,
mainname varchar(25) NOT NULL,
constructionyear smallint NOT NULL,
budget INTEGER NOT NULL
) ;
--
-- Dumping data for table `mainbank`
--
INSERT INTO mainbank (mainbankID, mainname, constructionyear, budget) VALUES
(1111, 'saderat', 1925, 20000000),
(2222, 'melli', 1912, 100000000);
-- --------------------------------------------------------
--
-- Table structure for table `managment`
--
CREATE TABLE managment (
managmentID INTEGER NOT NULL,
managename varchar(25) NOT NULL,
mphonenumber INTEGER NOT NULL,
manageaddress text NOT NULL,
manageage INTEGER NOT NULL,
manageedu varchar(100) NOT NULL,
msalary INTEGER NOT NULL,
employmentyear smallint NOT NULL,
branchID INTEGER NOT NULL
) ;
--
-- Dumping data for table `managment`
--
INSERT INTO managment (managmentID, managename, mphonenumber, manageaddress, manageage, manageedu, msalary, employmentyear, branchID) VALUES
(1030, 'akbar fallah', 2146258, 'tehran pol sadr', 59, 'Master of Banking', 2100000000, 2011, 516),
(1046, 'mohammad alavi', 352146, 'yazd blv jomhorii', 63, 'Master of Banking', 18200000, 2016, 215);
-- --------------------------------------------------------
--
-- Table structure for table `safebox`
--
CREATE TABLE safebox (
safeboxID INTEGER NOT NULL,
price INTEGER NOT NULL,
date date NOT NULL,
time time(0) NOT NULL,
branchID INTEGER NOT NULL
) ;
--
-- Dumping data for table `safebox`
--
INSERT INTO safebox (safeboxID, price, date, time, branchID) VALUES
(162, 75000000, '2020-11-07', '20:03:41', 123),
(888, 28000000, '2020-04-22', '10:00:00', 391),
(1642, 160000, '2019-01-25', '10:25:04', 215);
-- --------------------------------------------------------
--
-- Table structure for table `servise`
--
CREATE TABLE servise (
serviseID INTEGER NOT NULL,
sname varchar(25) NOT NULL,
Employmentyear smallint NOT NULL,
sage INTEGER NOT NULL,
sphone INTEGER NOT NULL,
saddress text NOT NULL,
ssalary INTEGER NOT NULL,
branchID INTEGER NOT NULL
) ;
--
-- Dumping data for table `servise`
--
INSERT INTO servise (serviseID, sname, Employmentyear, sage, sphone, saddress, ssalary, branchID) VALUES
(13333, 'iman', 1999, 49, 213620, 'tehran andishe', 30000, 516),
(15555, 'hesam', 2015, 38, 216201, 'tehran tajrish', 300000, 124);
and this is my whole code in MySQL:
-- phpMyAdmin SQL Dump
-- version 4.8.5
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jan 23, 2022 at 11:37 PM
-- Server version: 10.1.38-MariaDB
-- PHP Version: 7.3.3
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET #OLD_CHARACTER_SET_CLIENT=##CHARACTER_SET_CLIENT */;
/*!40101 SET #OLD_CHARACTER_SET_RESULTS=##CHARACTER_SET_RESULTS */;
/*!40101 SET #OLD_COLLATION_CONNECTION=##COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `bank`
--
-- --------------------------------------------------------
--
-- Table structure for table `account`
--
CREATE TABLE `account` (
`accountnumber` int(80) NOT NULL,
`balance` text COLLATE utf8_bin NOT NULL,
`date` date NOT NULL,
`time` time NOT NULL,
`branchID` int(25) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
--
-- Dumping data for table `account`
--
INSERT INTO `account` (`accountnumber`, `balance`, `date`, `time`, `branchID`) VALUES
(1132, 'توضیحات ترازنامه', '2021-07-12', '00:00:03', 516),
(1792, 'توضیحات ترازنامه', '2020-05-29', '11:17:27', 516),
(5130, 'توضیحات ترازنامه', '2016-02-23', '13:18:00', 123),
(7123, 'توضیحات ترازنامه', '2011-11-16', '10:25:00', 124),
(8210, 'توضیحات ترازنامه', '2019-01-11', '16:20:06', 215);
-- --------------------------------------------------------
--
-- Table structure for table `borrower`
--
CREATE TABLE `borrower` (
`customerID` int(50) NOT NULL,
`loanID` int(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
--
-- Dumping data for table `borrower`
--
INSERT INTO `borrower` (`customerID`, `loanID`) VALUES
(7951, 357),
(1089, 357);
-- --------------------------------------------------------
--
-- Table structure for table `branch`
--
CREATE TABLE `branch` (
`branchID` int(25) NOT NULL,
`bName` varchar(50) COLLATE utf8_bin NOT NULL,
`bCity` varchar(50) COLLATE utf8_bin NOT NULL,
`assests` bigint(20) NOT NULL,
`mainbankID` int(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
--
-- Dumping data for table `branch`
--
INSERT INTO `branch` (`branchID`, `bName`, `bCity`, `assests`, `mainbankID`) VALUES
(123, 'سعادت اباد', 'تهران', 250000000, 1111),
(124, 'تجریش', 'همدان ', 5842000, 2222),
(215, 'خیابان قیام', 'یزد', 700000000, 2222),
(391, 'نقش جهان', 'اصفهان', 20100000, 1111),
(516, 'میرداماد', 'تهران', 953200000, 1111);
-- --------------------------------------------------------
--
-- Table structure for table `customer`
--
CREATE TABLE `customer` (
`customerID` int(50) NOT NULL,
`CName` varchar(78) COLLATE utf8_bin NOT NULL,
`cphone number` int(11) NOT NULL,
`cCity` varchar(50) COLLATE utf8_bin NOT NULL,
`caddress` text COLLATE utf8_bin NOT NULL,
`cage` int(3) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
--
-- Dumping data for table `customer`
--
INSERT INTO `customer` (`customerID`, `CName`, `cphone number`, `cCity`, `caddress`, `cage`) VALUES
(412, 'معین سپهری', 387496, 'تهران', 'تهران شهرک غرب', 27),
(1089, 'سحر مقدم', 3254896, 'اصفهان', 'اصفهان پل خواجوو', 32),
(7951, 'ددا رضوی', 36232323, 'تهران', 'تهران شهرک اندیشه مجتمع رز', 26),
(463241, 'محمد فلاح', 3456213, 'یزد', 'یزد خیابان کاشانی کوچه علوی', 50);
-- --------------------------------------------------------
--
-- Table structure for table `depositor`
--
CREATE TABLE `depositor` (
`customerID` int(50) NOT NULL,
`accountnumber` int(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
--
-- Dumping data for table `depositor`
--
INSERT INTO `depositor` (`customerID`, `accountnumber`) VALUES
(7951, 7123),
(463241, 5130),
(412, 1132),
(463241, 1132),
(1089, 1132);
-- --------------------------------------------------------
--
-- Table structure for table `employee`
--
CREATE TABLE `employee` (
`EmployeeID` int(10) NOT NULL,
`Employeework` varchar(100) COLLATE utf8_bin NOT NULL,
`Employeename` varchar(25) COLLATE utf8_bin NOT NULL,
`aphonenumber` int(11) NOT NULL,
`Employmentyear` year(4) NOT NULL,
`eaddress` text COLLATE utf8_bin NOT NULL,
`esalary` int(20) NOT NULL,
`branchID` int(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
--
-- Dumping data for table `employee`
--
INSERT INTO `employee` (`EmployeeID`, `Employeework`, `Employeename`, `aphonenumber`, `Employmentyear`, `eaddress`, `esalary`, `branchID`) VALUES
(1551, 'Official', 'ali akbari', 912512123, 1941, 'tehran andarzgoo', 1400000000, 123),
(1881, 'Official', 'nazi imanii', 91352412, 1998, 'yazd kashani', 80000000, 215);
-- --------------------------------------------------------
--
-- Table structure for table `loan`
--
CREATE TABLE `loan` (
`loanID` int(50) NOT NULL,
`amount` int(50) NOT NULL,
`branchID` int(25) NOT NULL,
`startdate` date NOT NULL,
`enddate` date NOT NULL,
`time` time NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
--
-- Dumping data for table `loan`
--
INSERT INTO `loan` (`loanID`, `amount`, `branchID`, `startdate`, `enddate`, `time`) VALUES
(357, 300000, 516, '2020-01-02', '2022-01-12', '10:00:00'),
(412, 1230000, 215, '1998-08-25', '2021-11-25', '09:00:00'),
(863, 5400000, 516, '1996-08-13', '2020-12-30', '07:14:00');
-- --------------------------------------------------------
--
-- Table structure for table `mainbank`
--
CREATE TABLE `mainbank` (
`mainbankID` int(10) NOT NULL,
`mainname` varchar(25) COLLATE utf8_bin NOT NULL,
`constructionyear` year(4) NOT NULL,
`budget` int(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
--
-- Dumping data for table `mainbank`
--
INSERT INTO `mainbank` (`mainbankID`, `mainname`, `constructionyear`, `budget`) VALUES
(1111, 'saderat', 1925, 20000000),
(2222, 'melli', 1912, 100000000);
-- --------------------------------------------------------
--
-- Table structure for table `managment`
--
CREATE TABLE `managment` (
`managmentID` int(10) NOT NULL,
`managename` varchar(25) COLLATE utf8_bin NOT NULL,
`mphonenumber` int(11) NOT NULL,
`manageaddress` text COLLATE utf8_bin NOT NULL,
`manageage` int(3) NOT NULL,
`manageedu` varchar(100) COLLATE utf8_bin NOT NULL,
`msalary` int(20) NOT NULL,
`employmentyear` year(4) NOT NULL,
`branchID` int(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
--
-- Dumping data for table `managment`
--
INSERT INTO `managment` (`managmentID`, `managename`, `mphonenumber`, `manageaddress`, `manageage`, `manageedu`, `msalary`, `employmentyear`, `branchID`) VALUES
(1030, 'akbar fallah', 2146258, 'tehran pol sadr', 59, 'Master of Banking', 2100000000, 2011, 516),
(1046, 'mohammad alavi', 352146, 'yazd blv jomhorii', 63, 'Master of Banking', 18200000, 2016, 215);
-- --------------------------------------------------------
--
-- Table structure for table `safebox`
--
CREATE TABLE `safebox` (
`safeboxID` int(10) NOT NULL,
`price` int(20) NOT NULL,
`date` date NOT NULL,
`time` time NOT NULL,
`branchID` int(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
--
-- Dumping data for table `safebox`
--
INSERT INTO `safebox` (`safeboxID`, `price`, `date`, `time`, `branchID`) VALUES
(162, 75000000, '2020-11-07', '20:03:41', 123),
(888, 28000000, '2020-04-22', '10:00:00', 391),
(1642, 160000, '2019-01-25', '10:25:04', 215);
-- --------------------------------------------------------
--
-- Table structure for table `servise`
--
CREATE TABLE `servise` (
`serviseID` int(10) NOT NULL,
`sname` varchar(25) COLLATE utf8_bin NOT NULL,
`Employmentyear` year(4) NOT NULL,
`sage` int(3) NOT NULL,
`sphone` int(11) NOT NULL,
`saddress` text COLLATE utf8_bin NOT NULL,
`ssalary` int(20) NOT NULL,
`branchID` int(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
--
-- Dumping data for table `servise`
--
INSERT INTO `servise` (`serviseID`, `sname`, `Employmentyear`, `sage`, `sphone`, `saddress`, `ssalary`, `branchID`) VALUES
(13333, 'iman', 1999, 49, 213620, 'tehran andishe', 30000, 516),
(15555, 'hesam', 2015, 38, 216201, 'tehran tajrish', 300000, 124);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `account`
--
ALTER TABLE `account`
ADD PRIMARY KEY (`accountnumber`),
ADD KEY `branchID` (`branchID`);
--
-- Indexes for table `borrower`
--
ALTER TABLE `borrower`
ADD KEY `customerID` (`customerID`),
ADD KEY `loanID` (`loanID`);
--
-- Indexes for table `branch`
--
ALTER TABLE `branch`
ADD PRIMARY KEY (`branchID`);
--
-- Indexes for table `customer`
--
ALTER TABLE `customer`
ADD PRIMARY KEY (`customerID`);
--
-- Indexes for table `depositor`
--
ALTER TABLE `depositor`
ADD KEY `account number` (`accountnumber`),
ADD KEY `customerID` (`customerID`);
--
-- Indexes for table `employee`
--
ALTER TABLE `employee`
ADD PRIMARY KEY (`EmployeeID`),
ADD KEY `branchID` (`branchID`);
--
-- Indexes for table `loan`
--
ALTER TABLE `loan`
ADD PRIMARY KEY (`loanID`),
ADD KEY `branchID` (`branchID`);
--
-- Indexes for table `mainbank`
--
ALTER TABLE `mainbank`
ADD PRIMARY KEY (`mainbankID`);
--
-- Indexes for table `managment`
--
ALTER TABLE `managment`
ADD PRIMARY KEY (`managmentID`),
ADD KEY `branchID` (`branchID`);
--
-- Indexes for table `safebox`
--
ALTER TABLE `safebox`
ADD PRIMARY KEY (`safeboxID`),
ADD KEY `branchID` (`branchID`);
--
-- Indexes for table `servise`
--
ALTER TABLE `servise`
ADD PRIMARY KEY (`serviseID`),
ADD KEY `branchID` (`branchID`);
--
-- Constraints for dumped tables
--
--
-- Constraints for table `account`
--
ALTER TABLE `account`
ADD CONSTRAINT `account_ibfk_1` FOREIGN KEY (`branchID`) REFERENCES `branch` (`branchID`);
--
-- Constraints for table `borrower`
--
ALTER TABLE `borrower`
ADD CONSTRAINT `borrower_ibfk_1` FOREIGN KEY (`customerID`) REFERENCES `customer` (`customerID`),
ADD CONSTRAINT `borrower_ibfk_2` FOREIGN KEY (`loanID`) REFERENCES `loan` (`loanID`);
--
-- Constraints for table `depositor`
--
ALTER TABLE `depositor`
ADD CONSTRAINT `depositor_ibfk_1` FOREIGN KEY (`accountnumber`) REFERENCES `account` (`accountnumber`),
ADD CONSTRAINT `depositor_ibfk_2` FOREIGN KEY (`customerID`) REFERENCES `customer` (`customerID`);
--
-- Constraints for table `employee`
--
ALTER TABLE `employee`
ADD CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`branchID`) REFERENCES `branch` (`branchID`);
--
-- Constraints for table `loan`
--
ALTER TABLE `loan`
ADD CONSTRAINT `loan_ibfk_1` FOREIGN KEY (`branchID`) REFERENCES `branch` (`branchID`);
--
-- Constraints for table `managment`
--
ALTER TABLE `managment`
ADD CONSTRAINT `managment_ibfk_1` FOREIGN KEY (`branchID`) REFERENCES `branch` (`branchID`);
--
-- Constraints for table `safebox`
--
ALTER TABLE `safebox`
ADD CONSTRAINT `safebox_ibfk_1` FOREIGN KEY (`branchID`) REFERENCES `branch` (`branchID`);
--
-- Constraints for table `servise`
--
ALTER TABLE `servise`
ADD CONSTRAINT `servise_ibfk_1` FOREIGN KEY (`branchID`) REFERENCES `branch` (`branchID`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=#OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=#OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=#OLD_COLLATION_CONNECTION */;
First, you need to replace the backticks (`) with standard conforming double quotes ("). This will also prevent branchID from getting folded to lower case.
Second, instead of ALTER TABLE ... ADD KEY (colname) you have to use ALTER TABLE ... ADD UNIQUE (colname). You need a unique constraint as target of foreign key.
You can use this software for that purpose:
https://soft-builder.com/how-to-convert-mysql-database-to-postgresql/

Mysql complex select statement

I have a case which seems very complex to me and I am currently doing it in 3 queries and with lots of application logic. I thought, it may be possible with only one single queries.
I have a three table,
1. conversations table
2. chats table
3. users table
Please see the two pictures so that you can see the entities with the actual data.
conversations table
chats table
Please look at the conversation table. Here I want to get all the rows where sender=1 or reciever=1 so expected results will be
id 3,4,5. Now, I also return the user details from these selected rows.
Here is the most difficult part for me. I don't want to retrieve users details of id 1 instead I want users details whose id are 2,3 and 4 notice 4 in sender column and 2 3 in reciever column
Now, you know the selected rows from conversations table. In second table, con_id is the foreign key of conversation table so I want to retrieve the last rows of each con_id. In the second picture, you can see id 2,3,4,5,6 has con_id = 3 but since I want the last one so it should select where id = 6 similarly all last row of each con_id
I am sorry for this long case, hope you got me and the problem.
Thanks in advance.
EDIT
Here is the sql tables and dummy data for you so that if you want you can test paste quickly
Expected results
id || sender || reciver || id(users id) || userName || id(chats id) || con_id || msg || msg_sender
3 1 2 2 iamsadek2 6 3 ... 2
4 1 3 3 sadek3 10 4 ... 3
5 4 1 4 adek4. 14. 5. ... 4
DROP TABLE IF EXISTS `chats`;
CREATE TABLE `chats` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`msg_sender` int(10) unsigned DEFAULT NULL,
`con_id` int(10) unsigned DEFAULT NULL,
`msg` text,
`file` varchar(255) DEFAULT NULL,
`deleted` int(10) unsigned DEFAULT NULL,
`seen` tinyint(1) DEFAULT '0',
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `con_id` (`con_id`),
KEY `msg_sender` (`msg_sender`),
CONSTRAINT `chats_ibfk_1` FOREIGN KEY (`con_id`) REFERENCES `conversations` (`id`) ON DELETE CASCADE,
CONSTRAINT `chats_ibfk_2` FOREIGN KEY (`msg_sender`) REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
LOCK TABLES `chats` WRITE;
/*!40000 ALTER TABLE `chats` DISABLE KEYS */;
INSERT INTO `chats` (`id`, `msg_sender`, `con_id`, `msg`, `file`, `deleted`, `seen`, `created_at`, `updated_at`)
VALUES
(2,1,3,'id 1 sending msg to id 2',NULL,NULL,0,'2018-06-26 19:36:06',NULL),
(4,2,3,'id 2 sending msg to id 1 second msg',NULL,NULL,0,'2018-06-26 19:36:37',NULL),
(5,1,3,'id 1 sending msg to id 2 msg 3',NULL,NULL,0,'2018-06-26 19:36:42',NULL),
(6,2,3,'id 2 sending msg to id 1 msg 4',NULL,NULL,0,'2018-06-26 19:36:46',NULL),
(7,1,4,'id 1 sending msg to id 3 msg 1',NULL,NULL,0,'2018-06-26 19:36:49',NULL),
(8,3,4,'id 3 sending msg to id 1 msg 2am',NULL,NULL,0,'2018-06-26 19:39:44',NULL),
(9,3,4,'id 3 sending msg to id 1 msg 3',NULL,NULL,0,'2018-06-26 19:39:55',NULL),
(10,3,4,'id 3 sending msg to id 1 msg 4',NULL,NULL,0,'2018-06-26 19:39:57',NULL),
(11,4,5,'id 4 sending msg to id 1 msg 1',NULL,NULL,0,'2018-06-26 19:40:46',NULL),
(12,4,5,'id 4 sending msg to id 1 msg 1',NULL,NULL,0,'2018-06-26 19:40:48',NULL),
(13,4,5,'id 4 sending msg to id 1 msg 3',NULL,NULL,0,'2018-06-26 19:40:50',NULL),
(14,1,5,'id 1 sending msg to id 4 msg 4',NULL,NULL,0,'2018-06-26 19:41:01',NULL),
(15,4,11,'id 4 sending msg to id 3 msg 1',NULL,NULL,0,'2018-06-26 19:42:37',NULL),
(16,3,11,'id 3 sending msg to id 4 msg 2',NULL,NULL,0,'2018-06-26 19:42:57',NULL),
(17,3,11,'id 3 sending msg to id 4 msg 2',NULL,NULL,0,'2018-06-26 19:42:59',NULL);
/*!40000 ALTER TABLE `chats` ENABLE KEYS */;
UNLOCK TABLES;
# Dump of table conversations
# ------------------------------------------------------------
DROP TABLE IF EXISTS `conversations`;
CREATE TABLE `conversations` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`sender` int(10) unsigned DEFAULT NULL,
`reciever` int(10) unsigned DEFAULT NULL,
`status` tinyint(1) DEFAULT '0',
`type` tinyint(1) DEFAULT '0',
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `sender` (`sender`),
KEY `reciever` (`reciever`),
CONSTRAINT `conversations_ibfk_1` FOREIGN KEY (`sender`) REFERENCES `users` (`id`) ON DELETE CASCADE,
CONSTRAINT `conversations_ibfk_2` FOREIGN KEY (`reciever`) REFERENCES `users` (`id`) ON DELETE CASCADE,
CONSTRAINT `conversations_reciever_foreign` FOREIGN KEY (`reciever`) REFERENCES `users` (`id`),
CONSTRAINT `conversations_sender_foreign` FOREIGN KEY (`sender`) REFERENCES `users` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
LOCK TABLES `conversations` WRITE;
/*!40000 ALTER TABLE `conversations` DISABLE KEYS */;
INSERT INTO `conversations` (`id`, `sender`, `reciever`, `status`, `type`, `created_at`, `updated_at`)
VALUES
(3,1,2,0,0,'2018-06-26 19:32:35',NULL),
(4,1,3,0,0,'2018-06-26 19:32:50',NULL),
(5,4,1,0,0,'2018-06-26 19:33:11',NULL),
(6,2,3,0,0,'2018-06-26 19:33:22',NULL),
(11,3,4,0,0,'2018-06-26 19:33:22',NULL);
/*!40000 ALTER TABLE `conversations` ENABLE KEYS */;
UNLOCK TABLES;
# Dump of table users
# ------------------------------------------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`firstName` varchar(255) NOT NULL,
`lastName` varchar(255) NOT NULL,
`profilePic` varchar(255) DEFAULT 'user.png',
`address` varchar(255) DEFAULT NULL,
`lat` varchar(255) DEFAULT NULL,
`lang` varchar(255) DEFAULT NULL,
`ip` varchar(255) DEFAULT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`userName` varchar(255) NOT NULL,
`gender` varchar(11) DEFAULT NULL,
`userType` varchar(255) DEFAULT 'User',
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
`status` varchar(11) DEFAULT 'active',
PRIMARY KEY (`id`),
UNIQUE KEY `users_email_unique` (`email`),
UNIQUE KEY `users_username_unique` (`userName`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
LOCK TABLES `users` WRITE;
/*!40000 ALTER TABLE `users` DISABLE KEYS */;
INSERT INTO `users` (`id`, `firstName`, `lastName`, `profilePic`, `address`, `lat`, `lang`, `ip`, `password`, `email`, `userName`, `gender`, `userType`, `created_at`, `updated_at`, `status`)
VALUES
(1,'sadek','hossain','user.png',NULL,NULL,NULL,NULL,'$2a$10$ayAJE7BxkgqXPGjVxeD8iu0GVWL6CXJFdLhGcHAN.i39lCqcAR5nS','sadek.hkm#gmail.com','iamsadek','male','User','2018-06-26 18:33:16','2018-06-26 18:33:16','active'),
(2,'sadek2','hossain2','user.png',NULL,NULL,NULL,NULL,'$2a$10$q.LNN48POO9g1INdEC/iTO1CJjGXNBLYZPbHkyRe.oHaZJi9b8GWe','sadek2.hkm#gmail.com','iamsadek2','male','User','2018-06-26 18:42:53','2018-06-26 18:42:53','active'),
(3,'sadek3','hossain3','user.png',NULL,NULL,NULL,NULL,'$2a$10$7xgKQDUw/tA6f8zb0uqSN.z7RnNuUVAoMuB6Eknm/cqzXk7BDcmIi','sadek3#gmail.com','sadek3','male','User','2018-06-26 19:02:30','2018-06-26 19:02:30','active'),
(4,'sadek3','hossain3','user.png',NULL,NULL,NULL,NULL,'$2a$10$7xgKQDUw/tA6f8zb0uqSN.z7RnNuUVAoMuB6Eknm/cqzXk7BDcmIi','sadek4#gmail.com','sadek4','male','User','2018-06-26 19:02:30','2018-06-26 19:02:30','active'),
(5,'sadek3','hossain3','user.png',NULL,NULL,NULL,NULL,'$2a$10$7xgKQDUw/tA6f8zb0uqSN.z7RnNuUVAoMuB6Eknm/cqzXk7BDcmIi','sadek5#gmail.com','sadek5','male','User','2018-06-26 19:02:30','2018-06-26 19:02:30','active'),
(6,'sadek3','hossain3','user.png',NULL,NULL,NULL,NULL,'$2a$10$7xgKQDUw/tA6f8zb0uqSN.z7RnNuUVAoMuB6Eknm/cqzXk7BDcmIi','sadek6#gmail.com','sadek6','male','User','2018-06-26 19:02:30','2018-06-26 19:02:30','active');
/*!40000 ALTER TABLE `users` ENABLE KEYS */;
UNLOCK TABLES;
It can basically be done with some joins. The tricky part is the last message for chats. The subquery groups the chats by the con_id to get the maximum id. As id is AUTO_INCREMENT, the maximum id for a con_id is the last message of the conversation.
SELECT co1.id,
co1.sender,
co1.reciever,
us.id "id(users id)",
us.username,
ch1.id "id(chats id)",
ch1.con_id,
ch1.msg,
ch1.msg_sender
FROM conversations co1
INNER JOIN users us
ON CASE
WHEN co1.sender <> 1
THEN co1.sender
WHEN co1.reciever <> 1
THEN co1.reciever
END = us.id
INNER JOIN chats ch1
ON ch1.con_id = co1.id
INNER JOIN (SELECT max(ch2.id) id,
ch2.con_id
FROM chats ch2
GROUP BY ch2.con_id) ch3
ON ch3.con_id = ch1.con_id
AND ch3.id = ch1.id
WHERE 1 IN (co1.sender,
co1.reciever);
SQL Fiddle
Instead of an INNER JOIN with the subquery with the GROUP BY, a correlated subyquery would be another option.
SELECT co1.id,
co1.sender,
co1.reciever,
us.id "id(users id)",
us.username,
ch1.id "id(chats id)",
ch1.con_id,
ch1.msg,
ch1.msg_sender
FROM conversations co1
INNER JOIN users us
ON CASE
WHEN co1.sender <> 1
THEN co1.sender
WHEN co1.reciever <> 1
THEN co1.reciever
END = us.id
INNER JOIN chats ch1
ON ch1.con_id = co1.id
WHERE 1 IN (co1.sender,
co1.reciever)
AND ch1.id = (SELECT max(ch2.id)
FROM chats ch2
WHERE ch2.con_id = co1.id);
SQL Fiddle
TRy it now
SELECT id.conversations, sender.conversations, receiver.conversations, id.users, userName.users, id.chats, con_id.chats, msg.chats, msg_sender.chats
FROM conversations, chats, users
WHERE (sender.conversations OR receiver.conversations = 1) AND id.conversations=firstname.users
GROUP BY id.conversations

how can I get a field value in 3 association tables with the max of date

So, I have a table and I want to get the value from one field in the record with the greatest DateTime() value in another field and where still another field is equal to a certain value.
--
-- Structure de la table `site`
--
CREATE TABLE IF NOT EXISTS `site` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`site_name` varchar(15) NOT NULL,
`city` varchar(50) DEFAULT NULL,
`address` varchar(80) DEFAULT NULL,
`entity` varchar(50) DEFAULT NULL,
`status_activity` tinyint(1) NOT NULL DEFAULT '1',
`infra` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `idx_site_name` (`site_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
--
-- Contenu de la table `site`
--
INSERT INTO `site` (`id`, `site_name`, `city`, `address`, `entity`, `status_activity`, `infra`) VALUES
(1, 'FR001', 'tttt', 'tttttttttt', 'yyyyy', 1, 0),
(2, 'FR002', 'ccccc', 'cccccccccc', 'rrrrrrrrrrrr', 1, 0);
-- --------------------------------------------------------
--
-- Structure de la table `site_topology`
--
CREATE TABLE IF NOT EXISTS `site_topology` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`id_site` int(10) unsigned NOT NULL,
`id_topology` int(10) unsigned NOT NULL,
`date` date NOT NULL,
PRIMARY KEY (`id`),
KEY `idx_site_date` (`date`),
KEY `fk_id_site_2` (`id_site`),
KEY `fk_id_topology_2` (`id_topology`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ;
--
-- Contenu de la table `site_topology`
--
INSERT INTO `site_topology` (`id`, `id_site`, `id_topology`, `date`) VALUES
(1, 1, 1, '2015-03-03'),
(2, 2, 3, '2015-03-03'),
(3, 1, 2, '2015-04-30'),
(4, 2, 5, '2015-04-30'),
(5, 1, 1, '2015-06-25'),
(6, 2, 4, '2015-06-25');
-- --------------------------------------------------------
--
-- Structure de la table `topology`
--
CREATE TABLE IF NOT EXISTS `topology` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(10) NOT NULL,
PRIMARY KEY (`id`),
KEY `idx_type_name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ;
--
-- Contenu de la table `topology`
--
INSERT INTO `topology` (`id`, `name`) VALUES
(3, 'C1/C2'),
(2, 'C3'),
(5, 'HBN'),
(4, 'Infrastruc'),
(6, 'LB'),
(1, 'SHBN');
--
-- Contraintes pour les tables exportées
--
--
-- Contraintes pour la table `site_topology`
--
ALTER TABLE `site_topology`
ADD CONSTRAINT `fk_id_site_2` FOREIGN KEY (`id_site`) REFERENCES `site` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `fk_id_topology_2` FOREIGN KEY (`id_topology`) REFERENCES `topology` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
I want to see
FR001 SHBN 2015-06-26
FR002 Infrastruct 2015-06-26
but when I execute my query I have this
FR001 SHBN 2015-06-26`enter code here`
FR002 C1/C2 2015-06-26
Can anyone help me?
You had a problem on how to choose the max date, since the month was showing first. A different way is to bring up the max_date value (from a sub-query). After it you can compare by the different parts of the date. Code as follows:
select site_name, site_date, name
from
(
select site_name, st.date as site_date, name, s.id, (select max(sto.date) from site_topology sto) as max_date
from site s
inner join site_topology st on s.id =st.id_site
inner join topology t on st.id_topology = t.id
) as v
where YEAR(site_date) = YEAR(max_date) AND MONTH(site_date) = MONTH(max_date) AND DAY(site_date) = DAY(max_date)
group by name
order by site_name
Testing here.
use a subquery they're correct's aggregate Results here
select site_name,max(date), name
from
(select site_name,
city, address, entity , status_activity, infra,
st.*,name
from site s
inner join site_topology st on s.id =st.id_site
inner join topology t on st.id_topology = t.id )
as v
group by site_name

how to join Between four tables on mysql

i have 4 tables for mysql database, how i join Between them
users:
userid|username
1 | mark
2 | jon
awards_user :
awardid|userid
1 |1
2 |2
cat :
catid|catname
1 | english
2 | computer
awards :
awardid|catid|awardname|awardlink
1 |1 |best1 |pic link
2 |2 |best2 |pic link
resulte :
userid|username|catid|catname|awardid|awardname|awardlink
okay , that is my try :
works but Shows only one result, when there is a member holds a award
، I want to show all the awards, even if there is no one holds them .
$all_awards = $db->query_read(" SELECT * FROM " . TABLE_PREFIX . " users,awards_user,cat,awards
WHERE
awards_user.awardid = awards.awardid
AND
awards_user.userid = users.userid
AND
awards.catid = cat.catid
");
CREATE TABLE `awards` (
`id` int(10) unsigned NOT NULL auto_increment,
`forumid` int(10) unsigned NOT NULL,
`name` varchar(100) NOT NULL default '',
`link` varchar(100) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;
--
-- Dumping data for table `awards`
--
INSERT INTO `awards` VALUES (1, 2, 'award one', 'http://www.mwadah.com/pict/noway9.gif');
INSERT INTO `awards` VALUES (2, 1, 'award 2', 'http://www.forum-ksa.com/up/uploads/images/forum-ksac59a7122d1.gif');
-- --------------------------------------------------------
--
-- Table structure for table `awards_user`
--
CREATE TABLE `awards_user` (
`id` int(10) unsigned NOT NULL auto_increment,
`awardid` int(10) unsigned NOT NULL,
`userid` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `awards_user`
--
INSERT INTO `awards_user` VALUES (2, 2, 2);
-- --------------------------------------------------------
--
-- Table structure for table `forum`
--
CREATE TABLE `forum` (
`forumid` smallint(5) unsigned NOT NULL auto_increment,
`title` varchar(100) NOT NULL default '',
PRIMARY KEY (`forumid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=2;
--
-- Dumping data for table `forum`
--
INSERT INTO `forum` VALUES (1,'Main Category');
INSERT INTO `forum` VALUES (2,'Main Forum');
-- --------------------------------------------------------
--
-- Table structure for table `user`
--
CREATE TABLE `user` (
`userid` int(10) unsigned NOT NULL auto_increment,
`username` varchar(100) NOT NULL default ''
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `user`
--
INSERT INTO `user` VALUES (1,'admin');
INSERT INTO `user` VALUES (1,'mark');
You could structure your JOIN query like this:
SELECT *
FROM users
JOIN awards_user USING(userid)
JOIN awards USING(awardid)
JOIN cat USING(catid)
Then you can add a WHERE clause to filter the result.
SELECT awards.userid,
username,
awards.catid,
catname,
awards.awardid,
awardname,
awardlink
FROM users,
awards_user,
cat,
awards
WHERE awards_user.userid = users.userid
AND awards_user.awardid = awards.awardid
AND cat.catid = awards.catid;