简体   繁体   中英

SQL query to join two tables help

I have two tables one is heardt and other one is jud

In heardt i have three columns j1 , j2 , j3 (each has one value from jcode)

In jud i have jcode and jname .

I want to display jname in 3 different Dropdown list depending on j1 , j2 , j3 .

How do i frame my sql query.

I'm not sure I understand your question as the schema seems odd.

However, it sounds like you want to get:

  • Dropdown1 : Show jname where jcode is in a j1 cell in heardt
  • Dropdown2 : Show jname where jcode is in a j2 cell in heardt
  • Dropdown3 : Show jname where jcode is in a j3 cell in heardt

To do that your queries could be:

select jname, jcode
from heardt
inner join jud ON heardt.j1 = jcode

select jname, jcode
from heardt
inner join jud ON heardt.j2 = jcode

select jname, jcode
from heardt
inner join jud ON heardt.j3 = jcode

An alternative, that may interest you, is if you want to get for every heardt row and the three jnames that match it you could do this:

select jud1.jname as jname1, jud2.jname as jname2, jud3.jname as jname3
from heardt
left join jud as jud1 on jud1.jcode = heardt.j1
left join jud as jud2 on jud2.jcode = heardt.j2
left join jud as jud3 on jud3.jcode = heardt.j3

However, a better solution would be to make tables like these (pick better naming):

jud table
---------
jcode
jname

heardt table
------------
unsure on the purpose of this table

dropdown table (name this after whatever your dropdowns represent, maybe this is heardt)
----------
dropdownId

dropdownjuds table
-------------
dropdownId
jcode

That way you could do a query like below, and you aren't storing a column per dropdown. For instance, what if you suddenly need j4 later - with this method you could just add a new dropdown and relevant entries to the dropdownjuds table. What if the dropdowns have uneven numbers? You'd be using nulls currently I assume, but why have j1 and j3 columns if the row only has a j2 ? With the proposed design you'd get around this.

select jname 
from dropdownjuds ddj
inner join jud on ddj.jcode = jud.jcode
where dropdownId = *

Where * is 1 for dropdown1, 2 for dropdown2 etc.

If you elaborate the requirement (giving some data in the table and showing your expected output in terms of the same data), it would help.

If you wish to have a query to get the names for a set of input (j1, j2, j3), in that case you shall have to have inner queries or multiple joins.

select h.j1, hj1.jname, hj1.jcode, h.j2, hj2.jname, hj2.jcode, h.j3, hj3.jname, hj3.jcode
from heardt as h
inner join jud as hj1 ON h.j1 = hj1.jcode
inner join jud as hj2 ON h.j2 = hj2.jcode
inner join jud as hj3 ON h.j3 = hj3.jcode
where h.j1=@myj1 and h.j2=@myj2 and h.j3=@myj3

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