Note that there are some explanatory texts on larger screens.

plurals
  1. POJoin table to get the latest rows from unique row
    primarykey
    data
    text
    <p>I have two table</p> <p>The table structure goes something like this</p> <p>Table A</p> <pre><code>╔══════╦════════╗ ║ P_ID ║ P_NAME ║ ╠══════╬════════╣ ║ 1 ║ name1 ║ ║ 2 ║ name2 ║ ║ 3 ║ name3 ║ ║ 4 ║ name5 ║ ╚══════╩════════╝ </code></pre> <p>Table B</p> <pre><code>╔═════╦════════╦════════╦═══════════╦═══════╗ ║ ID ║ P_ID ║ C_ID ║ C_PRICE ║ TIME ║ ╠═════╬════════╬════════╬═══════════╬═══════╣ ║ 1 ║ 1 ║ 3 ║ 11 ║ 11111 ║ ║ 2 ║ 2 ║ 4 ║ 22 ║ 22222 ║ ║ 3 ║ 3 ║ 5 ║ 33 ║ 33333 ║ ║ 4 ║ 3 ║ 6 ║ 44 ║ 44444 ║ ║ 5 ║ 3 ║ 6 ║ 55 ║ 55555 ║ ║ 6 ║ 4 ║ 7 ║ 66 ║ 66666 ║ ╚═════╩════════╩════════╩═══════════╩═══════╝ </code></pre> <p>The requirement is <Br/> 1. Join two table <Br/> 2. Group By C_ID<Br/> 3. The latest rows in Group By<br/></p> <p>I tried to modify the answer By Bill Karwin from <a href="https://stackoverflow.com/questions/497535/how-do-i-join-the-most-recent-row-in-one-table-to-another-table/498179#498179">How do I join the most recent row in one table to another table?</a></p> <pre><code>SELECT e.*, s1.* FROM table_a e INNER JOIN table_b s1 ON (e.p_id = s1.p_id) LEFT OUTER JOIN table_b s2 ON (e.p_id = s2.p_id AND s1.id &lt; s2.id) WHERE s2.p_id IS NULL; </code></pre> <p>but I could not achieve what I want. From his answer I will get</p> <pre><code>╔═════╦════════╦════════╦═══════════╦═══════╦═════════╗ ║ ID ║ P_ID ║ C_ID ║ C_PRICE ║ TIME ║ P_NAME ║ ╠═════╬════════╬════════╬═══════════╬═══════╬═════════╣ ║ 1 ║ 1 ║ 3 ║ 11 ║ 11111 ║ name1 ║ ║ 2 ║ 2 ║ 4 ║ 22 ║ 22222 ║ name2 ║ ║ 5 ║ 3 ║ 6 ║ 55 ║ 55555 ║ name3 ║ ║ 6 ║ 4 ║ 7 ║ 66 ║ 66666 ║ name5 ║ ╚═════╩════════╩════════╩═══════════╩═══════╩═════════╝ </code></pre> <p>But the output what I want is as below ( dublicate P_ID is ok but for each dublicate P_ID should not have dublicate C_ID )</p> <pre><code>╔═════╦════════╦════════╦═══════════╦═══════╦═════════╗ ║ ID ║ P_ID ║ C_ID ║ C_PRICE ║ TIME ║ P_NAME ║ ╠═════╬════════╬════════╬═══════════╬═══════╬═════════╣ ║ 1 ║ 1 ║ 3 ║ 11 ║ 11111 ║ name1 ║ ║ 2 ║ 2 ║ 4 ║ 22 ║ 22222 ║ name2 ║ ║ 3 ║ 3 ║ 5 ║ 33 ║ 33333 ║ name3 ║ ║ 5 ║ 3 ║ 6 ║ 55 ║ 55555 ║ name3 ║ ║ 6 ║ 4 ║ 7 ║ 66 ║ 66666 ║ name5 ║ ╚═════╩════════╩════════╩═══════════╩═══════╩═════════╝ </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload