S
S
solid4772021-12-07 20:13:44
MySQL
solid477, 2021-12-07 20:13:44

How to display unique records from three tables?

Good day. Tell me please. I need to display unique records from three tables by ticker column. All three tables have the structure:

CREATE TABLE `table1` (
 `id` int(8) NOT NULL AUTO_INCREMENT,
 `ticker` varchar(16) NOT NULL,
 `lastprice` double NOT NULL,
 `pricechange` double NOT NULL,
 `pricechangepercent` float NOT NULL,
 `highprice` double NOT NULL,
 `lowprice` double NOT NULL,
 `volume` double NOT NULL,
 `quoteVolume` float NOT NULL,
 `spread` float NOT NULL,
 `time` varchar(22) NOT NULL,
 PRIMARY KEY (`id`),
 UNIQUE KEY `ticker` (`ticker`)
) ENGINE=InnoDB AUTO_INCREMENT=300 DEFAULT CHARSET=utf8

I do it like this:
SELECT * FROM table1 UNION SELECT * FROM table2 UNION SELECT * FROM table3

But in the end, all values ​​are displayed, and those that are repeated in the ticker column. I only want unique entries on the ticker column.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FirststepsRu, 2021-12-08
@FirststepsRu

Something does not come to mind in one request. It is necessary to merge all ticker values ​​into one table, then select only unique ones, and then select data from the main tables for them.
Something like this:

CREATE TEMPORARY TABLE all_ticker (`ticker` varchar(16) NOT NULL);
INSERT INTO all_ticker SELECT ticker FROM table1;
INSERT INTO all_ticker SELECT ticker FROM table2;
INSERT INTO all_ticker SELECT ticker FROM table3;

CREATE TEMPORARY TABLE uniq_ticker (`ticker` varchar(16) NOT NULL)
    SELECT ticker FROM all_ticker GROUP BY ticker HAVING count(*) = 1;

SELECT * FROM table1 t1 JOIN uniq_ticker u ON t1.ticker = u.ticker;
SELECT * FROM table2 t2 JOIN uniq_ticker u ON t2.ticker = u.ticker;
SELECT * FROM table3 t3 JOIN uniq_ticker u ON t3.ticker = u.ticker;

DROP TEMPORARY TABLE all_ticker, uniq_ticker;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question