Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Join Tables

Table one contains

ID|Name  
1  Mary  
2  John  

Table two contains

ID|Color  
1  Red  
2  Blue  
2  Green  
2  Black  

I want to end up with is

ID|Name|Red|Blue|Green|Black  
1  Mary Y   Y  
2  John     Y     Y     Y

Thanks for any help.


Thanks for the responses. I'm going to re-post this with some additional info about exactly what I'm trying to do that may complicate this. Can someone close this?

like image 938
Harley Avatar asked Mar 12 '10 14:03

Harley


People also ask

How can I join two tables in SQL?

The join is done by the JOIN operator. In the FROM clause, the name of the first table ( product ) is followed by a JOIN keyword then by the name of the second table ( category ). This is then followed by the keyword ON and by the condition for joining the rows from the different tables.

How do I join 4 tables in SQL query?

Here first, we will create the database using SQL query as follows. Now, we will use the database using SQL query as follows. Create a table 1, name as s_marks using SQL query as follows. Create a table2 for the professor details as p_details using SQL query as follows.

What are the 4 join types?

Four types of joins: left, right, inner, and outer.


2 Answers

If you use T-SQL you can use PIVOT (http://msdn.microsoft.com/en-us/library/ms177410.aspx)

Here is query I used:

declare @tbl_names table(id int, name varchar(100))
declare @tbl_colors table(id int, color varchar(100))

insert into @tbl_names
select 1, 'Mary'
union
select 2, 'John'


insert into @tbl_colors
select 1, 'Red'
union
select 1, 'Blue'
union
select 2, 'Green'
union
select 2, 'Blue'
union
select 2, 'Black'

select name,
        case when [Red] is not null then 'Y' else '' end as Red,
        case when [Blue] is not null then 'Y' else '' end as Blue,
        case when [Green] is not null then 'Y' else '' end as Green,
        case when [Black] is not null then 'Y' else '' end as Black

from
(
select n.id, name, color from @tbl_names n
inner join @tbl_colors c on n.id = c.id
) as subq
pivot 
(
    min(id)
    FOR color IN ([Red], [Blue], [Green], [Black])
) as pvt

And here is output:

John        Y   Y   Y
Mary    Y   Y       
like image 89
Andrew Bezzub Avatar answered Oct 26 '22 03:10

Andrew Bezzub


I can use a CASE statement with a subquery to input the Y values.

select ID, Name,
  case
    when exists (select * from Colors C where C.ID = N.ID and Color = 'Red') then
      'Y'
    else
      NULL
  end
,
 case
    when exists (select * from Colors C where C.ID = N.ID and Color = 'Blue') then
      'Y'
    else
      NULL
  end
,
 case
    when exists (select * from Colors C where C.ID = N.ID and Color = 'Green') then
      'Y'
    else
      NULL
  end
,
 case
    when exists (select * from Colors C where C.ID = N.ID and Color = 'Black') then
      'Y'
    else
      NULL
  end
from Names N
like image 20
AaronLS Avatar answered Oct 26 '22 03:10

AaronLS