Ask Your Question
2

Retrieve all rows in which two IDs appear for the first time.

asked 2022-09-28 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-01-27 20:00:00 +0000

djk gravatar image

It would depend on the specific database and table being used, but generally the query to retrieve all rows in which two IDs appear for the first time would involve using the DISTINCT and MIN functions to select the earliest occurrence of each ID, and then joining the results on a common ID field. For example, in MySQL syntax:

SELECT * FROM mytable WHERE id IN (SELECT DISTINCT MIN(id) FROM mytable GROUP BY id HAVING COUNT() = 1) OR other_id IN (SELECT DISTINCT MIN(other_id) FROM my_table GROUP BY other_id HAVING COUNT() = 1) JOIN (SELECT DISTINCT MIN(id) AS id1, MIN(otherid) AS otherid1 FROM mytable GROUP BY id, otherid HAVING COUNT(*) = 1) AS tmp ON mytable.id = tmp.id1 AND mytable.otherid = tmp.otherid1;

This query selects all rows where either the ID or otherID appears only once in the table (i.e. it is the first occurrence), and then joins them with all other rows where both the ID and otherID appear only once. The result is a table of all rows where both IDs appear for the first time.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-09-28 11:00:00 +0000

Seen: 13 times

Last updated: Jan 27 '23