I created two tables using MYSQL, tblorder and tblitem.
CREATE TABLE `tblorder` (
`orderId` int NOT NULL,
`orderName` varchar(45) NOT NULL,
PRIMARY KEY (`orderId`)
CREATE TABLE `tblitem` (
`itemId` int NOT NULL,
`itemName` varchar(45) NOT NULL,
`itemUnit` varchar(5) NOT NULL,
`itemRate` double NOT NULL,
`orderRef` int NOT NULL,
PRIMARY KEY (`itemId`),
KEY `fk1_idx` (`orderRef`),
CONSTRAINT `fk1` FOREIGN KEY (`orderRef`) REFERENCES `tblorder` (`orderId`)
I tried to join the two tables using query below
SELECT orderId,orderName, itemName, itemUnit,itemRate
FROM tblitem
INNER JOIN tblorder on tblorder.orderId = tblitem.orderRef
Now result show like Image-01
How to remove duplicate values in orderId ,OrderName columns in result table? Thanks to help me to solve this problem.
After joining tables is it possible to get output like below?
Output from new Query
Best Answer
Agreed with the other comments about handling this in the application side, as what you're looking for is more so presentation logic but this should accomplish it from the database side too:
This works by generating a unique ID (with the
ROW_NUMBER()
window function) within each group of rows perorderId
, ascending in the order of theitemId
(which is what your requested results show), which I call thesortId
. Then with thatsortId
you can check if the current row is the first item for that order, and then display the full row details, otherwise anything after the first item per order will blank out theorderId
andorderName
.By the way, I normally prefer to put each subquery into its own CTE instead for readability, but not sure which version of MySQL you're on and if it supports CTEs, so subqueries it is for now.