简体   繁体   中英

Best way to join this query

I have the following tables and data:

Tables
-----------
CREATE TABLE primarys 
( primaryid BIGINT(20) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (primaryid));

CREATE TABLE patients
( primaryid BIGINT(20) NOT NULL,
patientid BIGINT(20),
patientName VARCHAR(50),
PRIMARY KEY (primaryid));

CREATE TABLE patientvisit
( primaryid BIGINT(20) NOT NULL,
visitid BIGINT(20),
visitdate DATE,
PRIMARY KEY (primaryid));

Data
---------
INSERT INTO primarys values (1);
INSERT INTO primarys values (7286);
INSERT INTO primarys values (7287);

INSERT INTO patients VALUES (1,'1','John');
INSERT INTO patients VALUES (7286,'1', '');
INSERT INTO patients VALUES (7287,'1', '');

INSERT INTO patientvisit VALUES (7286,'1','1997-12-18');
INSERT INTO patientvisit VALUES (7287,'2','1998-02-25');

I need to write a query that outputs the data as follows:

primaryid   |  patientid    |   patientname    |  visit   |  visitdate
------------------------------------------------ 
7286        |   1           |  John            |   1      |  1997-12-18
7287        |   1           |  John            |   2      |  1998-02-25

I can figure out how to do this with outer joins and sub queries which work fine but when I start adding a large data set mysql performance begins to significantly decrease.

I would be very grateful if anyone could suggest the most optimised way to query these data and get the desired output.

Thanks

For the specific values you display in your question, this query would do.

SELECT q2.primaryid, q_1, q_2, q_4, q_5 FROM questions_101_200 q2
CROSS JOIN questions_1_100 

But your data and structure doesn't make much sense to me. If you explain more about what you are trying to do, I can give you a more meaningful answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM