I have a SQL query question that I have no idea whether it's achievable.
My database table structure: I have one table (TABLE A) is linked with second table (TABLE B) with the relationship of ONE TO MANY.
Problem Scenario: The ROW A in TABLE A is linked with 2 rows (ROWS A & ROW B) in TABLE B with different value in COLUMN A . The next row ROW B in TABLE A is linked with only 1 row (ROW C) in TABLE B. (Kindly refer to the following screenshot)
What I want:
- I want to retrieve the result that show column A value in
TABLE Band primary key value of the row inTABLE A. - Not allow multiple row with same primary key. In other word, only one column value should retrieve from
TABLE B(Even there's multiple rows inTABLE Bthat linked with one row inTABLE A). Due to this reason, when select the row inTABLE B, thecolumn Athat contain value of 2 will be taken first, the remaining rows will ignore. If thecolumn Aof each row inTABLE Bdoesn't contain the value of 2, then only it will select the row with value of 1.
Based on the above scenario, the expected result show look like this:
The following is the sample data:
-- create a table
CREATE TABLE tableA
(
id INTEGER PRIMARY KEY
);
CREATE TABLE tableB
(
id INTEGER PRIMARY KEY,
columnA INTEGER ,
fkid INTEGER,
FOREIGN KEY (fkid) REFERENCES tableA(id)
);
-- insert some values
INSERT INTO tableA VALUES (1);
INSERT INTO tableA VALUES (2);
INSERT INTO tableB VALUES (1, 1, 1);
INSERT INTO tableB VALUES (2, 2, 1);
INSERT INTO tableB VALUES (3, 1, 2);


